Benchmarks With ReportAllocs

Measure throughput and allocations with testing.B, ReportAllocs, and sub-benchmarks so optimization claims rest on numbers you can reproduce.

GoCli Tooling

Code

snippet
package bench

import (
	"strings"
	"testing"
)

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

func builder(parts []string) string {
	var b strings.Builder
	for _, part := range parts {
		b.WriteString(part)
		b.WriteByte(',')
	}
	return b.String()
}

// go test -bench=BenchmarkBuild -benchmem
// Sub-benchmarks compare both builders; ReportAllocs shows bytes and allocations per op.
func BenchmarkBuild(b *testing.B) {
	parts := []string{"alpha", "beta", "gamma", "delta", "epsilon"}

	b.Run("concat", func(b *testing.B) {
		b.ReportAllocs() // 记录每次操作的分配次数与字节数
		for i := 0; i < b.N; i++ {
			_ = concat(parts)
		}
	})

	b.Run("builder", func(b *testing.B) {
		b.ReportAllocs()
		for i := 0; i < b.N; i++ {
			_ = builder(parts)
		}
	})
}

How it works

The functional core is concat, builder and BenchmarkBuild — everything else is wiring.

Repetition is confined to for _, part := range parts — the rest of the file is straight-line.

What to watch for

  • Zero-fetch snippet: every identifier resolves inside the language distribution.

Putting it to use

What you call into: func BenchmarkBuild(b *testing.B)

BenchmarkBuild is what another module would consume; nothing else here is load-bearing for callers.

Core lines under the microscope

func builder(parts []string) string {
var b strings.Builder
for _, part := range parts {
b.WriteString(part)
b.WriteByte(',')
}
return b.String()
}
func concat(parts []string) string {
out := ""
for _, part := range parts {
out += part + ","
}
return out
}

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `concat`, `builder`, `BenchmarkBuild` at load time.