CodeBlanks Logo Icon CodeBlanks

Memory benchmark

Learn to measure memory usage with b.ReportAllocs.

Memory benchmarks

b.ReportAllocs() or the -benchmem flag shows bytes allocated per operation (B/op) and the allocation count (allocs/op). The allocation count is often more stable than time and is a direct indicator of GC pressure.

func BenchmarkBuilder(b *testing.B) {
    b.ReportAllocs()
    for i := 0; i < b.N; i++ {
        var sb strings.Builder
        sb.Grow(64)
        sb.WriteString("merhaba")
        sink = sb.String()
    }
}

An allocation test

You can lock in that a hot path doesn't allocate with a test; if someone accidentally adds an allocation, the test breaks:

func TestAnahtarAyirmasiz(t *testing.T) {
    n := testing.AllocsPerRun(100, func() { sink = anahtar(42) })
    if n != 0 {
        t.Fatalf("anahtar %v ayırma yaptı, 0 bekleniyordu", n)
    }
}

Practice Allocation-free key

Let anahtar(n int) int return n*31 + 7. Measure its allocations with testing.AllocsPerRun(100, ...) and print whether it is 0.

Starter code

main.go
package main

import (
    "fmt"
    "testing"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "testing"
)

var sink int

func anahtar(n int) int { return n*31 + 7 }

func main() {
    n := testing.AllocsPerRun(100, func() { sink = anahtar(42) })
    fmt.Println(n == 0)
}

Expected output

true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Outside a benchmark, what quickly gives a function's allocation count?

  • go vet
  • testing.AllocsPerRun Correct answer
  • runtime.NumGoroutine
  • time.Since

Explanation: AllocsPerRun runs the function several times and gives the average allocation count; tests use it to guarantee "zero allocations".

2 Report allocations

Question
func BenchmarkX(b *testing.B) {
    b.____()
    for i := 0; i < b.N; i++ { sink = x() }
}
Answer
func BenchmarkX(b *testing.B) {
    b.ReportAllocs()
    for i := 0; i < b.N; i++ { sink = x() }
}

Explanation: ReportAllocs prints B/op and allocs/op for this benchmark even without -benchmem.

3 Measurement tool

Term Meaning
-benchmem Memory for all benchmarks
b.ReportAllocs() Memory for one benchmark
testing.AllocsPerRun Allocation count in a test
allocs/op GC pressure indicator

All lessons in Intermediate