Skip to Content
Skip to content
Benchmark Speed and Heap Allocations With go test -bench -benchmem
Advanced
Tutorials

Benchmark Speed and Heap Allocations With go test -bench -benchmem

Measure nanoseconds and heap allocations with testing.B and -benchmem, compare += vs strings.Builder, pre-size slices, and reuse buffers with sync.Pool. After this, you optimize hot paths with measurements instead of guesses.

Updated 4 min read GoPerformance Optimization

Skip ahead: If you already write testing.B benchmarks, skip to "Case 2: cut allocations to zero with pre-sizing and sync.Pool" or the flags table below.

Optimizing Go code without a benchmark is guesswork. Go's built-in go test -bench -benchmem runner measures exact nanoseconds per operation (ns/op), heap bytes (B/op), and allocations (allocs/op), so you know immediately whether a change actually helped. Verified on golang:trixie (Go 1.27.4).

Case 1: compare += vs. strings.Builder

Joining 200 strings with += allocates a brand-new string on every iteration. strings.Builder appends into a growable byte slice instead:

// join.go
package join

import "strings"

func JoinPlus(parts []string) string {
	out := ""
	for _, p := range parts {
		out += p + ","
	}
	return out
}

func JoinBuilder(parts []string) string {
	var b strings.Builder
	for _, p := range parts {
		b.WriteString(p)
		b.WriteByte(',')
	}
	return b.String()
}
// join_test.go
package join

import "testing"

var sample = make([]string, 200)

func init() {
	for i := range sample {
		sample[i] = "item"
	}
}

func BenchmarkJoinPlus(b *testing.B) {
	for b.Loop() {
		_ = JoinPlus(sample)
	}
}

func BenchmarkJoinBuilder(b *testing.B) {
	for b.Loop() {
		_ = JoinBuilder(sample)
	}
}
go test -bench=. -benchmem -benchtime=200ms
goos: linux
goarch: amd64
pkg: example.com/bench
cpu: QEMU Virtual CPU version 2.5+
BenchmarkJoinPlus-2      	   12849	     16895 ns/op	  106440 B/op	     200 allocs/op
BenchmarkJoinBuilder-2   	  333706	       916.2 ns/op	    3320 B/op	       9 allocs/op
PASS
ok  	example.com/bench	0.526s

JoinBuilder ran roughly 18× faster (916.2 ns vs 16895 ns) and cut heap garbage from 106 KB (200 allocs/op) down to 3.3 KB (9 allocs/op).

Case 2: cut allocations to zero with pre-sizing and sync.Pool

When you already know a slice's size—or repeatedly borrow short-lived scratch buffers—pre-sizing with make([]T, 0, n) and reusing buffers with sync.Pool removes heap allocations altogether:

// pool_test.go
package allocs

import (
	"bytes"
	"sync"
	"testing"
)

var bufPool = sync.Pool{
	New: func() any { return new(bytes.Buffer) },
}

func BenchmarkSliceGrow(b *testing.B) {
	for b.Loop() {
		var s []int
		for i := range 256 {
			s = append(s, i)
		}
		_ = s
	}
}

func BenchmarkSlicePresized(b *testing.B) {
	for b.Loop() {
		s := make([]int, 0, 256)
		for i := range 256 {
			s = append(s, i)
		}
		_ = s
	}
}

func BenchmarkBufferPool(b *testing.B) {
	for b.Loop() {
		buf := bufPool.Get().(*bytes.Buffer)
		buf.Reset()
		buf.WriteString("hello-world")
		_ = buf.Len()
		bufPool.Put(buf)
	}
}
go test -bench=. -benchmem -benchtime=200ms
goos: linux
goarch: amd64
pkg: example.com/allocs
cpu: QEMU Virtual CPU version 2.5+
BenchmarkSliceGrow-2       	  355040	       637.6 ns/op	    4088 B/op	       9 allocs/op
BenchmarkSlicePresized-2   	 2563938	        98.44 ns/op	       0 B/op	       0 allocs/op
BenchmarkBufferPool-2      	25601575	        10.20 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	example.com/allocs	0.744s

Case 3: prevent compiler dead-code elimination

In Go 1.24+, using for b.Loop() excludes setup code automatically and keeps the compiler from optimizing away the result of your benchmarked function. On older Go versions, assign results to a package-level sink variable or call b.ResetTimer() after setup.

Benchmark flags worth knowing

FlagWhat it doesWhen to use
-bench=.Runs all Benchmark* functions (pass -run=^$ to skip unit tests)Focused benchmark runs
-benchmemPrints B/op and allocs/opAlways, when hunting GC pressure
-count=5Runs 5 samples so you can compare with benchstatBefore/after comparisons on noisy machines
-cpuprofile=cpu.profWrites a profile for go tool pprofWhen you want to see where time went inside the benchmark

⚠ Warning: Never run benchmarks with -race enabled—race instrumentation slows execution several times over and distorts every timing number.

Common mistakes

  • Running 1-sample benchmarks on a busy laptop: use -count=5 or compare relative orders of magnitude rather than chasing 2% noise.
  • Forgetting buf.Reset() with sync.Pool: reusing a dirty buffer leaks data from an earlier caller into the next response.

What happens if you skip this

You spend days micro-optimizing a function that ran once at startup while leaving a += loop or un-sized slice allocating gigabytes per minute on every request.

Related course: Go Advanced.

About

Measure nanoseconds and heap allocations with testing.B and -benchmem, compare += vs strings.Builder, pre-size slices, and reuse buffers with sync.Pool. After this, you optimize hot paths with measurements instead of guesses.

Responsible
Jay P
Last Update
11/27/2026
Reading Time
4 min
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.