Go (Golang) Tutorial 0/45 lessons ~6 min read Lesson 36

    Benchmark Testing

    Benchmarks measure performance with func BenchmarkXxx(b testing.B).

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Benchmarks measure performance with func BenchmarkXxx(b *testing.B). Go runs benchmarks with increasing iteration counts until stable timing. Compare implementations with benchstat, profile with pprof, and detect allocations with ReportAllocs.

    Benchmarks matter in Go interviews for high-throughput services — JSON serialization, cache lookups, and string building are common targets. Understanding ns/op, B/op (bytes allocated), and allocs/op metrics guides optimization decisions.

    This lesson benchmarks string concatenation vs strings.Builder and demonstrates memory allocation reporting — skills that differentiate mid-level backend engineers.

    The story

    A Cloudflare JSON serialization hot path processes millions of edge config updates per minute. Before switching marshalers, engineers write benchmarks: go test -bench=. compares encoding/json vs alternatives, reporting ns/op and allocations/op — data that drives decisions worth millions in CPU savings across global infrastructure.

    Benchmarks prevent premature optimization but validate it: profile first, benchmark the change, deploy with confidence.

    Understanding the topic

    Key concepts

    • func BenchmarkName(b *testing.B) in *_test.go.
    • b.N iterations adjusted automatically by framework.
    • b.ResetTimer() excludes setup from measurement.
    • b.ReportAllocs() shows allocations per operation.
    • go test -bench=. -benchmem runs benchmarks.
    • benchstat compares two benchmark runs statistically.

    Step-by-step explanation

    1. Benchmark function loops b.N times calling code under test.
    2. Setup before loop; b.ResetTimer() before measured section.
    3. go test -bench=BenchmarkFoo -count=5 for stable results.
    4. pprof: go test -bench=. -cpuprofile=cpu.out.
    5. Compare before/after optimization with benchstat.
    6. Benchmark parallel with b.RunParallel for concurrent code.

    Practical code example

    Benchmark comparing string concat vs Builder with allocation reporting:

    go
    package main
    import (
    "strings"
    "testing"
    )
    func concatLoop(n int) string {
    s := ""
    for i := 0; i < n; i++ {
    s += "x"
    }
    return s
    }
    func builderLoop(n int) string {
    var b strings.Builder
    b.Grow(n)
    for i := 0; i < n; i++ {
    b.WriteByte('x')
    }
    return b.String()
    }
    func BenchmarkConcat(b *testing.B) {
    b.ReportAllocs()
    for i := 0; i < b.N; i++ {
    concatLoop(100)
    }
    }
    func BenchmarkBuilder(b *testing.B) {
    b.ReportAllocs()
    for i := 0; i < b.N; i++ {
    builderLoop(100)
    }
    }

    Output

    goos: darwin
    goarch: arm64
    pkg: example.com/strbench
    cpu: Apple M2
    BenchmarkConcat-8    	  534902	      2112 ns/op	    5664 B/op	      99 allocs/op
    BenchmarkBuilder-8   	 5661409	       211.0 ns/op	     112 B/op	       1 allocs/op
    PASS
    ok  	example.com/strbench	4.038s

    Line-by-line code explanation

    • s += "x" appends one character to a string. Go strings cannot be changed in place, so each pass builds a new string and copies the old contents into it.
    • var b strings.Builder declares a Builder, a type made for assembling a string piece by piece in a growable byte buffer.
    • b.Grow(n) reserves space for n bytes up front, so the builder does not have to reallocate its buffer as it fills.
    • b.WriteByte('x') appends one byte to the buffer. It does not copy the text built so far, unlike the += version.
    • return b.String() returns the finished string without copying the buffer.
    • func BenchmarkConcat(b *testing.B) { is a benchmark. Go treats functions named Benchmark... that take *testing.B in a _test.go file as benchmarks and runs them with go test -bench.
    • b.ReportAllocs() adds memory allocation counts and bytes per operation to the benchmark output next to the time, which is where the two approaches differ most.
    • for i := 0; i < b.N; i++ { repeats the work b.N times. The testing package picks b.N, increasing it until the timing is stable.
    • builderLoop(100) is the timed work in BenchmarkBuilder: building a 100-character string with the Builder. BenchmarkConcat does the same with concatLoop, so the results are directly comparable.

    Key takeaway: Save the code as strings_test.go and run go test -bench=. -benchmem. Builder shows fewer allocs/op. b.Grow preallocates capacity. The output below was measured on an Apple M2 — iteration counts and ns/op vary by machine, but the allocation counts (99 vs 1) are stable.

    Real-world use

    Where you'll use this in production

    • Optimizing JSON marshal hot paths in APIs.
    • Comparing cache implementations before production.
    • Validating regex vs string ops for log parsing.
    • CI regression detection on critical path latency.

    Best practices

    • Benchmark before optimizing — profile proves bottleneck.
    • Use b.ReportAllocs() for allocation-sensitive code.
    • Run with -count=5 and compare with benchstat.
    • Reset timer after expensive setup.
    • Benchmark realistic input sizes from production metrics.
    • Don't micro-optimize without benchmark evidence.

    Common mistakes

    • Benchmarking debug builds — use consistent flags.
    • Including setup in timed section without ResetTimer.
    • Single run conclusions — high variance misleads.
    • Optimizing cold paths ignoring pprof top functions.
    • Benchmarking on laptop while CI runs on different CPU.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    5 questions
    1BeginnerQuestionRun benchmarks?+

    Answer

    go test -bench=. -benchmem ./...
    2BeginnerQuestionb.N meaning?+

    Answer

    Iteration count auto-tuned for reliable timing measurement.
    3IntermediateQuestionReportAllocs purpose?+

    Answer

    Shows bytes and allocation count per operation — GC pressure indicator.
    4IntermediateQuestionpprof from benchmarks?+

    Answer

    go test -bench=. -cpuprofile=cpu.out; go tool pprof cpu.out.
    5AdvancedQuestionOptimize JSON API handler latency.+

    Answer

    pprof CPU+heap; benchmark marshal; pool buffers; reduce allocations; cache read-heavy data.

    Summary

    Benchmarks measure ns/op and allocations with testing.B. Always benchmark before optimizing; use pprof for proof. strings.Builder beats += in loops — verify with benchmem. benchstat compares runs; -race separate from benchmarks. Next lesson: structured logging with slog.

    Ready to mark this lesson complete?Track your journey across the entire course.