Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

⚡ Optimize App.buildTree() #1809

Merged
merged 2 commits into from
Mar 7, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
⚡ Optimize App.buildTree()
- Reduces reads from / writes to slices
- Reduces reads from maps
- Increases sorting speed
  • Loading branch information
jfcg committed Mar 5, 2022
commit 84ad31af46d91201eca3f71b9ec7123bde4bb28d
15 changes: 8 additions & 7 deletions router.go
Original file line number Diff line number Diff line change
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