Skip to content

fix: reduce slice allocations in route dispatch #710

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

alespour
Copy link

@alespour alespour commented Apr 9, 2025

This PR makes handlers slice reused in router.matchAndDispatch in order to reduce slice (re)allocations. I think it is safe to reuse the slice since it is only used when order = true. Therefore, also added explicit if order check for iterating over handlers, although it is safe to keep iterating over nil slice when order = false, of course.

It is only a subtle optimization, but appeared when I profiled high-load scenario.

Benchmark with a single route:

before:

go test -v -run Benchmark_MatchAndDispatch -bench=. -benchmem -benchtime=10s

Benchmark_MatchAndDispatch-4   	13364338	       884.3 ns/op	     136 B/op	       3 allocs/op

after:

go test -v -run Benchmark_MatchAndDispatch -bench=. -benchmem -benchtime=10s

Benchmark_MatchAndDispatch-4   	14650513	       808.3 ns/op	     128 B/op	       2 allocs/op

I suppose with more routes, without reusing the slice, append would cause more re-allocations.

@alespour alespour closed this Apr 9, 2025
@alespour alespour reopened this Apr 9, 2025
@alespour alespour marked this pull request as ready for review April 9, 2025 13:00
Signed-off-by: Ales Pour <ales.pour@bonitoo.io>
Signed-off-by: Ales Pour <ales.pour@bonitoo.io>
@alespour alespour force-pushed the fix/reduce-route-dispatch-allocations branch from 067bbff to ee146f3 Compare April 10, 2025 14:38
@alespour alespour changed the title fix: reduce route dispatch allocations fix: reduce slice allocations in route dispatch Apr 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant