Skip to content

Go Test Bench Alloc

DodaTech 1 min read

In this tutorial, you'll learn about Go Test: Benchmark Allocations. We cover key concepts, practical examples, and best practices.

Benchmark allocations -- Use -benchmem flag or b.ReportAllocs to measure and reduce memory allocations.

The Problem

High allocation rates increase GC pressure and slow down your application. Benchmarks can measure allocations per operation.

Wrong

func BenchmarkProcess(b *testing.B) {
    for i := 0; i < b.N; i++ {
        process()
    }
}

Output:

$ go test -bench=BenchmarkProcess
BenchmarkProcess-8    1000000  1500 ns/op
// No allocation info
func BenchmarkProcess(b *testing.B) {
    b.ReportAllocs()
    for i := 0; i < b.N; i++ {
        process()
    }
}

Output:

$ go test -bench=BenchmarkProcess -benchmem
BenchmarkProcess-8    1000000  1500 ns/op  256 B/op  3 allocs/op

Prevention

  • Use -benchmem or b.ReportAllocs() for allocation stats
  • B/op = bytes allocated per operation
  • allocs/op = number of allocations per operation
  • Reduce allocations with object pooling (sync.Pool)
  • Pre-allocate slices with make([]T, 0, expectedLen)

Common Mistakes with test bench alloc

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**What is a good allocations target?**

0 allocs/op is ideal. Under 5 is good for most operations.

How to find where allocations happen?

Use go test -benchmem -bench=... or pprof alloc profiles.

Does inlining affect allocations?

Yes. Inlining can eliminate allocations. Check with -gcflags=-m.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro