~/Benchmarking In Go
Aug 22, 2025
1. Structure of a Go Benchmark
2. Running Benchmarks
- Run all benchmarks:
go test -bench .
- Run specific benchmarks:
go test -bench 'Pattern'
- Change default time per benchmark:
go test -bench . -benchtime 3s
3. Prevent Compiler Optimizations
- Assign return values to a package-level variable to avoid function calls being optimized away:
5. Expensive Setup
- Use
b.ResetTimer()
after setup code to exclude setup from timing.
6. Measuring Allocations
- Show memory usage:
go test -bench . -benchmem
7. Example Use Case
- Comparing set intersection using different types (
[]string
,map[string]bool
,map[string]struct{}
) shows how benchmarks yield data on speed and memory use.
8. Interpreting Results
- More iterations = lower noise.
- Look for execution time (
ns/op
) and allocations (B/op
,allocs/op
). - Run multiple times for reliability.
Tips
- Use benchmarking in Go to guide performance decisions.
- Structure functions with
b *testing.B
. - Prevent code from being optimized away.
- Run with
go test -bench .
(add-benchmem
for allocations). - Focus on real-world bottlenecks; optimize thoughtfully.