Skip to content

Benchmarks

These numbers measure the container alone: every service is a pointer that is already built, so what’s left is the cost of finding it. In every benchmark the container holds 32 services, about what an app wires at startup, and the one read is in the middle of them.

Both versions ran on the same harness. v1’s Invoke calls are measured against the v2 calls that replace them: where v1 handed a service to a func through reflection, v2’s Get returns it typed. With 16 goroutines at once, the time is the wall time divided by all of their reads, as go test reports it: it measures throughput, not how long one read takes.

Time per read, lower is better
Show as a table
Time per read: time and allocations, v1 against v2
Scenariov1v2
Get5.8 ns0 allocs3.6 ns0 allocs
Get, not registered4.8 ns0 allocs3.3 ns0 allocs
MustGet6.4 ns0 allocs3.5 ns0 allocs
Has6.2 ns0 allocs3.4 ns0 allocs

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

v1 read under a read-write lock. Every reader writes to the lock’s shared counter, so readers on different cores queue for it, and reading from 16 goroutines at once cost more per read than reading from one. v2 keeps its services in a map it never changes once it’s published: a read is an atomic load and a lookup, and readers don’t touch anything another core writes.

The price is on the other side. To change the map, Register and Deregister copy it and swap the copy in, so they are slower than v1’s and grow with the number of services. Services are registered once, at startup, and read for as long as the program runs, so v2 makes that trade.

BenchmarkTimeMemoryAllocations
GetGet a registered service3.5 ns0 B0
GetNotRegisteredGet under a key with nothing registered3.4 ns0 B0
MustGetMustGet a registered service3.4 ns0 B0
HasCheck for a registered service3.3 ns0 B0
GetParallelGet from 16 goroutines at once0.26 ns0 B0
Register/1Replace the only service52.7 ns264 B3
Register/32Replace one of 32 services216.8 ns1888 B5
Register/1024Replace one of 1024 services4.71 µs54664 B7

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 fails if a call allocates more than it should.