go 18 lines · 1 tab

Benchmarking hot paths (allocs and throughput)

Leah Thompson Jan 2026
1 tab
package hotpath

import "testing"

func BenchmarkParse(b *testing.B) {
  b.ReportAllocs()
  payload := []byte("id=123&status=active&limit=50")

  b.ResetTimer()
  for i := 0; i < b.N; i++ {
    _ = parse(payload)
  }
}

func parse(_ []byte) map[string]string {
  // placeholder for the thing you actually benchmark
  return map[string]string{"ok": "true"}
}
1 file · go Explain with highlit

When latency matters, I benchmark the smallest interesting unit and watch allocations. In Go, a surprising number of regressions come from accidental heap churn: converting []byte to string, building lots of temporary maps, or using fmt.Sprintf in loops. A benchmark with b.ReportAllocs() and b.ResetTimer() gives you fast feedback. The other key is realism: seed representative payload sizes so the benchmark reflects production. Once a baseline exists, it’s easy to see whether a refactor made things worse. I also like to run benchmarks with -benchmem and keep an eye on allocs/op; it’s often a better leading indicator than raw ns/op. Benchmarks aren’t for micro-optimizing everything—just the paths you call millions of times.


Related snips

Share this code

Here's the card — post it anywhere.

Benchmarking hot paths (allocs and throughput) — share card
Link copied