Benchmark With B.Loop

Replace the manual for-i-less-than-b.N loop with b.Loop on Go 1.24: iteration count, timer reset, and memory stats are handled automatically.

GoCli Tooling

Code

snippet
package main

import (
	"fmt"
	"strings"
	"testing"
)

// 目标函数:把逗号分隔的标签拆开、去掉空白再重新拼接
func normalizeTags(raw string) string {
	parts := strings.Split(raw, ",")
	for i := range parts {
		parts[i] = strings.TrimSpace(parts[i])
	}
	return strings.Join(parts, ",")
}

func BenchmarkNormalizeTags(b *testing.B) {
	// Go 1.24 的 b.Loop:迭代次数、计时器重置与内存统计自动处理。
	// 不再手写 for i := 0; i < b.N; i++,也不会忘记 ResetTimer。
	for b.Loop() {
		_ = normalizeTags("go, rust, typescript, python, ruby")
	}
}

func main() {
	fmt.Println("benchmark with: go test -bench=. .")
	fmt.Println(normalizeTags("go, rust, typescript"))
}

How the pieces interact

Benchmark With B.Loop comes down to the functions normalizeTags, BenchmarkNormalizeTags and main.

A single loop drives the file — for i := range parts.

What to watch for

  • No packages come from outside the language; every piece leans on its built-in APIs.

Using it

Signature: func BenchmarkNormalizeTags(b *testing.B)

The demo output is labeled (benchmark with: go test -bench=. .); each label names the call that printed it.

Running the file executes main, which drives normalizeTags in order.

Key statements

func BenchmarkNormalizeTags(b *testing.B) {
	// Go 1.24 的 b.Loop:迭代次数、计时器重置与内存统计自动处理。
	// 不再手写 for i := 0; i < b.N; i++,也不会忘记 ResetTimer。
	for b.Loop() {
		_ = normalizeTags("go, rust, typescript, python, ruby")
	}
}
func normalizeTags(raw string) string {
	parts := strings.Split(raw, ",")
	for i := range parts {
		parts[i] = strings.TrimSpace(parts[i])
	}
	return strings.Join(parts, ",")
}
func main() {
	fmt.Println("benchmark with: go test -bench=. .")
	fmt.Println(normalizeTags("go, rust, typescript"))
}

Interactive Tools for This Topic

FAQ

What does Benchmark With B.Loop print when run?
Execute the whole file; each printed line is prefixed with a label like `benchmark with: go test -bench=. .`.