typestar

Benchmarks in Go

b.Loop in Go 1.24 replaced the b.N loop, and stops the optimizer cheating.

func Join(parts []string) string {
    var b strings.Builder
    for i, part := range parts {
        if i > 0 {
            b.WriteString(",")
        }
        b.WriteString(part)
    }
    return b.String()
}

func BenchmarkJoin(b *testing.B) {
    parts := strings.Split(strings.Repeat("step,", 50), ",")
    b.ReportAllocs()

    for b.Loop() {
        _ = Join(parts)
    }
}

func BenchmarkStdlibJoin(b *testing.B) {
    parts := strings.Split(strings.Repeat("step,", 50), ",")
    for b.Loop() {
        _ = strings.Join(parts, ",")
    }
}

How it works

  1. for b.Loop() runs the body enough times to be meaningful.
  2. b.ReportAllocs adds allocations per operation.
  3. Setup before the loop is not timed.

Keywords and builtins used here

The run, in numbers

Lines
26
Characters to type
452
Tokens
142
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 77 seconds.

Type this snippet

Step 1 of 3 in Measuring & generating, step 8 of 13 in Testing.

← Previous Next →