Back to Blog

Benchmarks & Profiling: Measure Performance with pprof | Go Tutorial #30

Sandy LaneSandy Lane

Video: Benchmarks & Profiling: Measure Performance with pprof | Go Tutorial #30 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Benchmarks & Profiling: Measure Performance with pprof in Go

Benchmarking and profiling are essential techniques for optimizing Go programs. Go’s built-in testing package provides a straightforward way to write benchmarks and analyze performance, while the pprof tool helps identify CPU bottlenecks. This guide covers writing benchmarks, interpreting results, and using CPU profiling to improve your code.

Code

package main

import (
  "fmt"
  "strings"
  "testing"
)

// Benchmark using + operator for string concatenation
func BenchmarkConcatPlus(b *testing.B) {
  for i := 0; i < b.N; i++ {
    _ = "Hello " + "World"
  }
}

// Benchmark using fmt.Sprintf
func BenchmarkSprintf(b *testing.B) {
  for i := 0; i < b.N; i++ {
    _ = fmt.Sprintf("%s %s", "Hello", "World")
  }
}

// Benchmark using strings.Builder (most efficient)
func BenchmarkBuilder(b *testing.B) {
  for i := 0; i < b.N; i++ {
    var sb strings.Builder
    sb.WriteString("Hello ")
    sb.WriteString("World")
    _ = sb.String()
  }
}

// Table-driven benchmark comparing different input sizes
func BenchmarkStringRepeat(b *testing.B) {
  tests := []struct {
    name string
    n    int
  }{
    {"Small", 10},
    {"Medium", 1000},
    {"Large", 100000},
  }

  for _, tt := range tests {
    b.Run(tt.name, func(b *testing.B) {
      for i := 0; i < b.N; i++ {
        _ = strings.Repeat("a", tt.n)
      }
    })
  }
}

Key Points

  • Benchmark functions use the signature func BenchmarkX(b *testing.B) and run loops based on b.N iterations.
  • Go 1.24+ introduces b.Loop() as a modern alternative to the classic for loop over b.N.
  • Run benchmarks with go test -bench=. Use -benchmem to see memory allocations and -count to repeat runs.
  • Table-driven benchmarks with b.Run allow testing multiple input sizes or scenarios cleanly within one benchmark.
  • CPU profiling with go test -cpuprofile=cpu.out and analyzing via go tool pprof helps identify hotspots and optimize performance.