Go

Benchmarks with testing.B

admin by @admin ADMIN
Jun 16, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`BenchmarkXxx(b *testing.B)` functions are run by `go test -bench`. `b.N` is the loop count the framework auto-tunes; report results in ns/op, allocs/op.
Go
Raw
package mypkg

import "testing"

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

func Concat2(parts []string) string {
    var b strings.Builder
    for _, p := range parts { b.WriteString(p) }
    return b.String()
}

// ─────────────────────────────
// mypkg_test.go

var input = make([]string, 1000)
func init() {
    for i := range input { input[i] = "hello" }
}

func BenchmarkConcat(b *testing.B) {
    for i := 0; i < b.N; i++ {
        _ = Concat(input)
    }
}

func BenchmarkConcat2(b *testing.B) {
    b.ReportAllocs()                          // include alloc info in output
    for i := 0; i < b.N; i++ {
        _ = Concat2(input)
    }
}

// Run:
//   go test -bench=. -benchmem
// Sample output:
//   BenchmarkConcat-8     500    2934821 ns/op  4587123 B/op  999 allocs/op
//   BenchmarkConcat2-8  50000      24013 ns/op    18432 B/op    8 allocs/op
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.