Benchmark Assigns b.N

ID

go.benchmark_assigns_bn

Severity

low

Remediation Complexity

simple

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Go

Tags

CWE:1164, benchmark, reliability, testing

Description

Reports an assignment to b.N — the benchmark iteration count — inside a Benchmark* function.

Rationale

b.N is owned by the testing framework. The benchmark runner adapts it across runs, increasing it until the benchmark executes long enough to be timed reliably, and then uses the final value to compute per-operation timings. Overwriting b.N from inside the benchmark breaks that feedback loop: the reported numbers no longer correspond to the work actually measured, and results become non-reproducible. The benchmark body should only ever read b.N (typically as a loop bound).

func BenchmarkFoo(b *testing.B) {
    b.N = 1000 // FLAW — distorts the measurement
    for i := 0; i < b.N; i++ {
        work()
    }
}

Remediation

Remove the assignment and let the framework manage b.N; use a fixed local constant if a specific inner iteration count is needed.