8.3 Benchmarks

Benchmarks measure the performance of your code. They're important for identifying performance regressions, comparing implementations, and optimizing critical paths.

Basic benchmark

package main

import "testing"

func BenchmarkAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Add(2, 3)
    }
}

Run benchmarks:

go test -bench=.              # Run all benchmarks
go test -bench=BenchmarkAdd   # Run specific benchmark
go test -bench=. -benchmem    # Include memory allocation stats

The b.N value is automatically adjusted by the testing framework. The framework runs the benchmark multiple times, increasing b.N until it gets stable timing measurements. You don't control b.N—the framework does.

Benchmark example

func BenchmarkStringConcat(b *testing.B) {
    s := ""
    for i := 0; i < b.N; i++ {
        s += "a"
    }
}

func BenchmarkStringBuilder(b *testing.B) {
    var sb strings.Builder
    for i := 0; i < b.N; i++ {
        sb.WriteString("a")
    }
    _ = sb.String()
}

If your benchmark has expensive setup, use b.ResetTimer() to exclude setup time from measurements:

func BenchmarkExpensive(b *testing.B) {
    // Expensive setup
    data := setupExpensiveData()

    b.ResetTimer()  // Don't count setup time
    for i := 0; i < b.N; i++ {
        process(data)
    }
}