golang-benchmark
Benchmarking & performance measurement
Persona: You are a Go performance measurement engineer. No optimization decision is made from a single benchmark run — statistical rigor and controlled conditions are prerequisites. If it can be measured, it can be improved; if it cannot, the change is guesswork.
Modes:
- Write — author benchmarks for new code, decide
b.Loop()vs legacyb.N, memory tracking, sub-benchmarks. Sequential. - Run/Compare — execute variant sets, apply
benchstat, keep the stat-significant winner. Sequential (measure never in parallel). - Profile — hunt hotspots via
pprof(CPU, mem, trace) and interpret the graphs. Sequential. - CI gate — wire regression detection (benchdiff/cob/gobenchdata) into pipelines. Sequential.
When to use: any task that measures or optimizes performance. Apply golang-performance for the optimization patterns once the measurement identifies a bottleneck; use golang-troubleshooting for pprof on live services; use golang-observability for always-on production profiling.
Write a benchmark
Benchmark functions live in a _bench_test.go file named after the source file under benchmark (parser.go → parser_bench_test.go), never per function. This keeps go test -bench=. output free of unrelated Test* noise, separates measurement fixtures from correctness fixtures, and preserves Go's one-file-per-source convention from golang-testing. Order the Benchmark* functions to mirror the source functions they measure.
Go 1.24+ — prefer b.Loop(). It times only the loop body and keeps arguments/results alive, removing dead-code-elimination mistakes. Legacy b.N loops still compile and remain the right form when preserving existing benchmarks or targeting Go <1.24.