Benchmarks and profiling

Write a BenchmarkX

A benchmark lives in a test file and its name starts with Benchmark. The testing framework calls it with a B value, and the loop over b.N repeats the measured code until timing stabilizes.

Good benchmarks compare two approaches to one task. The file below joins words with plain concatenation and with a strings.Builder, so one run shows which method wins.

package main import ( "strings" "testing" ) func JoinPlus(parts []string) string { out := "" for _, p := range parts { out += p } return out } func BenchmarkJoinPlus(b *testing.B) { parts := []string{"go", "is", "fast"} for i := 0; i < b.N; i++ { JoinPlus(parts) } } func BenchmarkJoinBuilder(b *testing.B) { parts := []string{"go", "is", "fast"} for i := 0; i < b.N; i++ { var sb strings.Builder for _, p := range parts { sb.WriteString(p) } _ = sb.String() } }

go test -bench

The go test tool runs benchmarks when the bench flag matches their names. A dot matches every benchmark, run with NONE skips unit tests, and benchtime controls the workload per benchmark.

Each result line shows the name, the iteration count, and the average time per operation. Smaller time per operation wins, so the Builder line below beats plain concatenation.

go test -bench=. -benchtime=100x -run=NONE

BenchmarkJoinPlus-8 100 420 ns/op

BenchmarkJoinBuilder-8 100 310 ns/op

pprof basics

Timing tells which function is slow, while a profile tells which line inside it burns the time. The test tool writes a CPU profile to a file when the cpuprofile flag points at one.

The go tool pprof command opens that file for questions. The top command lists the hottest functions first, and the list command with a function name shows time per source line.

go test -bench=Builder -cpuprofile=cpu.out -run=NONE

BenchmarkJoinBuilder-8 100 310 ns/op

ok wordfreq 0.412s

go tool pprof -top cpu.out

Type: cpu

Time: Oct 6, 2026

main.JoinBuilder

Watch allocations

Speed is only half the story. Every heap allocation costs the garbage collector future work, so benchmarks should track bytes and allocation counts next to time.

The benchmem flag adds two columns to each result line: bytes per operation and allocations per operation. Fewer allocations often predict calmer production behavior under load.

go test -bench=. -benchmem -run=NONE

BenchmarkJoinPlus-8 100 420 ns/op 64 B/op 3 allocs/op

BenchmarkJoinBuilder-8 100 310 ns/op 24 B/op 1 allocs/op

For a focused check, AllocsPerRun measures one function in isolation. It runs the closure many times and returns the average allocation count as a float.

package main import ( "testing" ) func BenchmarkConcatAllocs(b *testing.B) { parts := []string{"go", "is", "fast"} n := testing.AllocsPerRun(100, func() { out := "" for _, p := range parts { out += p } }) b.ReportMetric(n, "allocs") }

Next: Toolchain and CI

Article author: Arthur Isaev

Banner image