BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Benchmarking

Go 1.23

Measure and optimize code performance with Go's built-in Benchmarking tools. This example demonstrates how to write benchmark functions, interpret the results, and use them to make data-driven optimization decisions.

Code

// main_test.go
package main

import (
    "fmt"
    "testing"
)

func IntMin(a, b int) int {
    if a < b {
        return a
    }
    return b
}

func BenchmarkIntMin(b *testing.B) {
    for i := 0; i < b.N; i++ {
        IntMin(1, 2)
    }
}

// Example of benchmarking string concatenation
func BenchmarkStringConcat(b *testing.B) {
    for i := 0; i < b.N; i++ {
        s := ""
        for j := 0; j < 100; j++ {
            s += "a"
        }
    }
}

func BenchmarkSprintf(b *testing.B) {
    for i := 0; i < b.N; i++ {
        s := ""
        for j := 0; j < 100; j++ {
            s = fmt.Sprintf("%s%s", s, "a")
        }
    }
}

Explanation

Benchmarking helps you measure the performance of your code. Benchmark functions start with Benchmark and take a *testing.B parameter.

Best practices for accurate benchmarks:

  • Reset Timer: Use b.ResetTimer() if you have expensive setup code before the loop that shouldn't be measured.
  • Report Allocs: Run with go test -bench=. -benchmem or call b.ReportAllocs() to see memory allocation statistics (bytes/op and allocs/op). Zero allocations is often a goal for hot paths.
  • Loop Correctness: Always use the b.N value in your loop. The testing framework adjusts N dynamically to get a statistically significant measurement.

Code Breakdown

15
Benchmark functions must accept a *testing.B parameter. This provides the N field and methods for timing control (ResetTimer, StopTimer, StartTimer).
16
The core loop: for i := 0; i < b.N; i++. The code inside this loop is what's being measured. b.N starts small (e.g., 1) and increases (100, 10000, etc.) until the function runs for at least 1 second.
22
BenchmarkStringConcat tests naive string concatenation using +=. This is generally inefficient in Go because it creates a new string for every addition.
31
BenchmarkSprintf tests string building using fmt.Sprintf. Comparing the results of these two benchmarks would show which method is more performant.