From 870f9427a224a976f435ce497b6a9871b5714e61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Serhat=20=C5=9Eevki=20Din=C3=A7er?= Date: Mon, 7 Mar 2022 21:01:30 +0300 Subject: [PATCH] :zap: Optimize App.buildTree() (#1809) * :zap: Optimize App.buildTree() - Reduces reads from / writes to slices - Reduces reads from maps - Increases sorting speed * :watch: Add Benchmark_Startup_Process() --- router.go | 15 ++++++++------- router_test.go | 9 +++++++++ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/router.go b/router.go index 4190771bcf..e7764546f7 100644 --- a/router.go +++ b/router.go @@ -447,27 +447,28 @@ func (app *App) buildTree() *App { } // loop all the methods and stacks and create the prefix tree for m := range intMethod { - app.treeStack[m] = make(map[string][]*Route) + tsMap := make(map[string][]*Route) for _, route := range app.stack[m] { treePath := "" if len(route.routeParser.segs) > 0 && len(route.routeParser.segs[0].Const) >= 3 { treePath = route.routeParser.segs[0].Const[:3] } // create tree stack - app.treeStack[m][treePath] = append(app.treeStack[m][treePath], route) + tsMap[treePath] = append(tsMap[treePath], route) } + app.treeStack[m] = tsMap } // loop the methods and tree stacks and add global stack and sort everything for m := range intMethod { - for treePart := range app.treeStack[m] { + tsMap := app.treeStack[m] + for treePart := range tsMap { if treePart != "" { // merge global tree routes in current tree stack - app.treeStack[m][treePart] = uniqueRouteStack(append(app.treeStack[m][treePart], app.treeStack[m][""]...)) + tsMap[treePart] = uniqueRouteStack(append(tsMap[treePart], tsMap[""]...)) } // sort tree slices with the positions - sort.Slice(app.treeStack[m][treePart], func(i, j int) bool { - return app.treeStack[m][treePart][i].pos < app.treeStack[m][treePart][j].pos - }) + slc := tsMap[treePart] + sort.Slice(slc, func(i, j int) bool { return slc[i].pos < slc[j].pos }) } } app.routesRefreshed = false diff --git a/router_test.go b/router_test.go index ac92f16b70..d8a8c323f4 100644 --- a/router_test.go +++ b/router_test.go @@ -582,6 +582,15 @@ func Benchmark_Router_WithCompression(b *testing.B) { } } +// go test -run=^$ -bench=Benchmark_Startup_Process -benchmem -count=9 +func Benchmark_Startup_Process(b *testing.B) { + for n := 0; n < b.N; n++ { + app := New() + registerDummyRoutes(app) + app.startupProcess() + } +} + // go test -v ./... -run=^$ -bench=Benchmark_Router_Next -benchmem -count=4 func Benchmark_Router_Next(b *testing.B) { app := New()