Skip to content

Benchmarks

These numbers measure the router alone: handlers and middleware do nothing, so what’s left is the cost of matching, params and dispatch. Your handlers will dominate a real request; the point is that the router adds as little as possible.

Both versions ran on the same harness, with the same routes and requests.

Time to route one request on net/http, lower is better
Show as a table
Time and allocations to route one request on net/http, v4 against v5
Scenariov4v5
Static route20.0 ns0 allocs19.9 ns0 allocs
Static, 5 segments28.5 ns0 allocs30.2 ns0 allocs
One param87.0 ns4 allocs93.6 ns2 allocs
Three params + regexp150.1 ns4 allocs148.5 ns2 allocs
Static + 3 middleware170.4 ns6 allocs23.8 ns0 allocs
One param + 3 middleware238.4 ns10 allocs100.8 ns2 allocs
404 Not Found20.0 ns0 allocs20.3 ns0 allocs
405 Method Not Allowed60.8 ns3 allocs55.8 ns2 allocs

Apple M4 Max, Go 1.27.0, median of 5 runs.

The biggest gains are behind middleware: v4 composed each route’s middleware chain on every request, v5 composes it once at registration. On fasthttp, v5 also stopped allocating for params, 404s and literal routes.

Each row routes one request, except API, which averages a request across a realistic 70-route REST API.

BenchmarkTimeMemoryAllocations
Static/1One literal segment15.0 ns0 B0
Static/5Five literal segments31.6 ns0 B0
Static/20Twenty literal segments98.8 ns0 B0
Param/1One param90.3 ns336 B2
Param/5Five params132.2 ns336 B2
Param/20Twenty params883.4 ns2137 B7
Regexp/1One regexp param157.6 ns336 B2
Regexp/5Five regexp params434.8 ns336 B2
MiddlewareLiteral route behind 3 middleware23.1 ns0 B0
NotFound40418.9 ns0 B0
MethodNotAllowed405 with an Allow header55.7 ns32 B2
MountRequest through a mounted router83.0 ns448 B1
APIAverage over a 70-route API95.5 ns226 B1.3

Up to eight param values fit in a buffer on the stack; a router with a longer route takes a pooled buffer instead, so it still allocates nothing.

From a clone of the repository:

Terminal window
go test -run '^$' -bench . -benchmem ./...

To compare two versions, run each a few times and compare with benchstat:

Terminal window
go test -run '^$' -bench . -count 10 ./... > new.txt
benchstat old.txt new.txt

The allocation counts are also enforced by tests: TestAllocations in each router package fails if a request allocates more than it should.