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.
Code
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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
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=. .`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.