Skip to Content
Skip to content
Go Advanced: Performance, Concurrency, and Production
Advanced
Courses
Go Advanced: Performance, Concurrency, and Production

Measure Speed and Allocations With go test -bench

Write Go benchmarks with testing.B, enable allocation reporting with -benchmem, and compare string concatenation vs strings.Builder. After this, you can measure changes instead of guessing.

Course content

Sign in to save your progress.

Course Home

Optimizing Go code by intuition almost always wastes an afternoon: you make a cold function harder to read while leaving a hidden allocation loop untouched on the hot path. Go's built-in benchmarking harness (go test -bench with -benchmem) lets you measure both execution time (ns/op) and garbage-collector pressure (B/op, allocs/op) in seconds.

Skip ahead

If you already write benchmarks with Go 1.24+'s for b.Loop(), track allocations with -benchmem, and compare multiple runs with benchstat, move on to "Cut Allocations With Pre-Sizing and sync.Pool."

Experiment 1: Benchmarking a real HTTP path normalizer

Suppose your metrics middleware normalizes request paths like /users/42/orders/991 into /users/:id/orders/:id so Prometheus does not explode with millions of high-cardinality labels. Compare compiling the regex inside the function (normalizeSlow) against compiling it once at package scope (normalizeFast):

package norm

import (
	"regexp"
	"testing"
)

func normalizeSlow(path string) string {
	re := regexp.MustCompile(`/[0-9]+`)
	return re.ReplaceAllString(path, "/:id")
}

var idRe = regexp.MustCompile(`/[0-9]+`)

func normalizeFast(path string) string {
	return idRe.ReplaceAllString(path, "/:id")
}

func BenchmarkNormalizeSlow(b *testing.B) {
	for b.Loop() {
		_ = normalizeSlow("/users/42/orders/991")
	}
}

func BenchmarkNormalizeFast(b *testing.B) {
	for b.Loop() {
		_ = normalizeFast("/users/42/orders/991")
	}
}
$ go test -run=^$ -bench=. -benchmem -benchtime=200ms .
goos: linux
goarch: amd64
pkg: example.com/adv5
BenchmarkNormalizeSlow-2   	  281642	       785.9 ns/op	    1565 B/op	      22 allocs/op
BenchmarkNormalizeFast-2   	 1210044	       197.6 ns/op	      96 B/op	       5 allocs/op

Experiment 2: Reading every column—and why allocs/op matters more than you think

Read the four result columns from left to right:

  • 281642 vs. 1210044: Iterations completed inside the 200 ms budget.
  • 785.9 ns/op → 197.6 ns/op: 4× faster per call.
  • 1565 B/op → 96 B/op and 22 allocs/op → 5 allocs/op: Moving one line out of the function eliminated 17 heap allocations per request—cutting garbage-collector pressure by 94%.

In real Go web services, reducing allocs/op often lowers p99 latency far more than shaving 50 ns of pure CPU time, because fewer allocations mean fewer GC mark/sweep cycles across all goroutines.

Experiment 3: Why Go 1.24+'s for b.Loop() beats the old for i := 0; i < b.N; i++

Older Go benchmarks required writing b.ResetTimer() after setup and assigning results to a package-level sink variable so the compiler wouldn't dead-code-eliminate the benchmark body. Go 1.24's for b.Loop() fixes both automatically:

  • Setup code placed before for b.Loop() is automatically excluded from timing.
  • The compiler is prevented from optimizing away function calls inside the loop body.

Experiment 4: Comparing before and after reliably with benchstat

A single benchmark run on a busy laptop can easily swing ±15% due to background processes or CPU thermal throttling. Always capture 6–10 samples before and after your change and compare them statistically with benchstat:

$ go test -run=^$ -bench=BenchmarkNormalize -benchmem -count=6 > old.txt
# ... apply optimization ...
$ go test -run=^$ -bench=BenchmarkNormalize -benchmem -count=6 > new.txt
$ go run golang.org/x/perf/cmd/benchstat@latest old.txt new.txt

benchstat computes the median, variance, and p-value so you know whether a 5% change is real or noise.

Common mistakes

  • Omitting -run=^$: Causes slow unit tests to run before your benchmarks every time.
  • Omitting -benchmem: Hides allocation regressions—an "optimization" that saves 20 ns while adding 4 allocations per call can hurt real production latency.
  • Benchmarking on tiny 3-item inputs when production processes 10,000 items: O(n²) string concatenation looks fine at n=5 and explodes at n=500. Use sub-benchmarks (b.Run("n=200", ...)) across realistic sizes.

💡 Tip

Pass -cpu=1,4 to see whether a concurrent benchmark scales cleanly across multiple cores or stalls under lock contention.

What happens if you skip this step

Without baseline benchmarks and -benchmem, teams complicate readable code with "optimizations" that save nothing—or accidentally introduce new heap allocations on the hottest path in the service.

You change a helper function, run go test -bench=. -count=1 once, and see a 4% drop in ns/op. Why shouldn't you trust that single run yet, and what two flags give you reliable proof?

About

Write Go benchmarks with testing.B, enable allocation reporting with -benchmem, and compare string concatenation vs strings.Builder. After this, you can measure changes instead of guessing.

Duration
5 min
Last update
11/27/2026
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.