Skip to content

Commit

Permalink
⚡ Optimize App.buildTree() (#1809)
Browse files Browse the repository at this point in the history
* ⚡ Optimize App.buildTree()

- Reduces reads from / writes to slices
- Reduces reads from maps
- Increases sorting speed

* ⌚ Add Benchmark_Startup_Process()
  • Loading branch information
jfcg committed Mar 7, 2022
1 parent 10fa3ef commit 870f942
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
15 changes: 8 additions & 7 deletions router.go
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions router_test.go
Expand Up @@ -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()
Expand Down

0 comments on commit 870f942

Please sign in to comment.