Category: Performance and measurement

Four of five loops had no bounds check to remove

The compiler eliminated every check in four spellings of the same sum. The folklore hint changed nothing, and the one surviving check cost less than the harness's own error.

A top compiler block connects left to a diamond decision node linked to panic, and right to four vertically stacked benchmark loops.

TL;DR

  1. `-gcflags=-d=ssa/check_bce/debug=1` printed one line for a file containing five loops. Four of them compile with no bounds check at all, including the plain indexed one the hint is meant to fix.
  2. The `_ = s[len(s)-1]` hint measured 0.87% slower than the loop without it. A second copy of that same loop measured 1.45% slower than itself, so the hint is inside its own control pair.
  3. The one check that survives is in the loop whose bound is a separate parameter, because the compiler cannot relate that parameter to the slice. That is the shape the hint would help, and it is not the shape anyone writes it in.
  4. That loop was also the fastest row at −1.10%, which is inside the control too. A bounds check on a perfectly predicted branch costs less than this benchmark can resolve.
  5. The useful output is the compiler's, not the benchmark's. One build answers whether there was ever a check to remove.

I built a file containing five loops over the same slice and asked the compiler which bounds checks it kept.

$ go build -gcflags='-d=ssa/check_bce/debug=1' ./bce
# gopheria.lab/bce
bce/loops.go:61:11: Found IsInBounds

One line. Four of the five have no bounds check to eliminate, including the plain indexed loop that _ = s[len(s)-1] is supposed to fix.

What is being measured

All numbers: go1.27.0 darwin/arm64, Apple M4 Pro, 12 cores, macOS 26.6.2. The harness is bce/.

Five spellings of one sum. Every one returns the same value for the same input:

func Indexed(s []uint64) uint64 {
	var sum uint64
	for i := 0; i < len(s); i++ {
		sum += s[i]
	}
	return sum
}

func Hinted(s []uint64) uint64 {
	if len(s) == 0 {
		return 0
	}
	_ = s[len(s)-1]        // the folklore
	var sum uint64
	for i := 0; i < len(s); i++ {
		sum += s[i]
	}
	return sum
}

func Bounded(s []uint64, n int) uint64 {
	var sum uint64
	for i := 0; i < n; i++ {   // n is not len(s), and the compiler knows it
		sum += s[i]
	}
	return sum
}

Plus Ranged (for i := range s) and RangedValue (for _, v := range s). Those three are excerpts; in the file itself line 61 is sum += s[i] inside Bounded, which is the one line the compiler flagged.

The benchmark below carries Indexed twice, as a control pair. Everything this post concludes rests on that second row, because every difference it measures turns out to be smaller than the one the harness invents.

The hint removes nothing

The prove pass had already eliminated the check in Indexed. The loop condition is i < len(s) and the index is i, which is the easiest possible thing to prove, and the compiler proves it. Adding _ = s[len(s)-1] above that loop asserts something already known.

Ranged and RangedValue are easier still: range produces the index, so it is in bounds by construction.

That leaves Bounded, where the bound arrives as a separate int. The compiler cannot relate n to len(s) — a caller could pass anything — so the check stays. That is the shape the hint would help, and it is not the shape anyone writes it in, because the hint asserts a fact about len(s) and the loop is not bounded by len(s).

Reading the flag’s output

Found IsInBounds is one of two things the pass reports. IsInBounds is an index expression — s[i] — and IsSliceInBounds is a slice expression — s[i:j], which has a looser condition because the upper bound may equal the length. Neither appeared anywhere in this file except that one line, and a file with no surviving checks produces no output at all beyond the package header.

The column matters as much as the line. loops.go:61:11 is column 11, which is the s[i] inside Bounded’s loop body rather than the loop header — the check belongs to the indexing expression, not to the comparison that failed to prove it away.

What it costs

$ go test -run=^$ -bench='Warmup|Sum' -benchmem -count=10 ./bce |
    grep -v Warmup | benchstat -row /n -col /form -
        │   indexed   │ indexed-control │    ranged    │ ranged-value │    hinted    │   bounded    │
0064      17.89n ± 0%   +0.92% (p=0.015)  ~ (p=0.836)   +1.03% (0.000)  +2.24% (0.000)  -1.03% (0.000)
1024      266.0n ± 0%   +2.05% (p=0.000)  ~ (p=0.540)   +1.30% (0.000)  +1.32% (0.000)  -1.15% (0.000)
4096      1.040µ ± 0%   +1.39% (p=0.000)  ~ (p=0.264)   +3.80% (0.000)  ~ (p=0.084)     -1.11% (0.000)
geomean   170.4n        +1.45%            -0.04%        +2.04%          +0.87%          -1.10%

indexed-control is a second row for Indexed — the same function, measured twice in the same run, so its true delta is zero. It came back 1.45% slower than itself, with two of its three rows at p=0.000.

That number is the bar, and it is the whole table’s verdict. The hint is +0.87%. ranged is −0.04%. bounded is −1.10%. Every one of them is smaller in magnitude than the difference the harness produces from identical code. Only ranged-value at +2.04% clears it, and barely.

Nothing here is a result, and that is the answer to the question. If the hint did what the folklore says, this table would show it; if a surviving bounds check were expensive, bounded would be the slow row. It is the fast one, by an amount that is also noise.

The ranged row is worth its own line: −0.04% geomean, ~ on all three lengths, which is as close to identical as this table gets. for i := range s with s[i] inside compiles to the same thing as the plain indexed loop, so choosing between them is a readability question with no performance component at all — which is not what most style arguments about it assume.

This is the control pair doing the only job it has. Without it, hinted at +0.87% with p=0.000 on two rows reads as a finding — a small, statistically significant regression from adding the hint. With it, the same numbers say the benchmark cannot see the difference.

Why a surviving check is nearly free

bounded keeps a check and is not slower for it, which is worth a sentence of mechanism rather than a shrug.

A bounds check is a compare against the length and a conditional branch to a panic. The branch is taken zero times in a loop that stays in bounds, so a branch predictor that has seen the loop once gets it right every iteration afterwards, and a correctly predicted not-taken branch costs approximately the issue slot it occupies. On a machine this wide, that slot was free.

The compare is not free in principle — it is an instruction — but at 4096 elements the loop is memory-bound, and an extra integer compare disappears behind the loads.

Ask the compiler instead

The practical shape of this is not a benchmark at all:

go build -gcflags='-d=ssa/check_bce/debug=1' ./yourpackage

Every surviving check gets a line with a file and a column. Silence means the prove pass removed them. It is one build, it takes no statistics, and it answers the question directly — where the benchmark can only tell you the effect is smaller than its own error.

That is the same move as asking the compiler what a construct costs instead of guessing: the information exists, it is one flag away, and the folklore persists because nobody looked.

What this does not measure

One loop shape, one element type, one machine. uint64 sums are as predictable as loops get; a loop with data-dependent branches inside it, or one over a slice of structs, gives the compiler and the predictor different problems.

Nested indexing is also absent — s[i][j] and slice-of-slice access are where surviving checks actually accumulate, and where the debug flag earns its keep. This file has none of that.

And nothing here says the hint is harmful. It costs a line and, on this evidence, nothing else. What it does not do is what it is written for, and the version of it that would help is one nobody has written down.

Frequently asked

Does _ = s[len(s)-1] actually eliminate bounds checks?

In the loop shapes people write it in, there is nothing to eliminate. Building the file below with -gcflags=-d=ssa/check_bce/debug=1 reported exactly one surviving check across five loops, and it was not in the plain indexed loop, the range loop, the range-with-value loop, or the hinted one. The hint removes a check the compiler had already proved away.

What does a surviving bounds check cost in Go?

Less than a laptop benchmark resolves. The one loop here that keeps a check — its length comes in as a separate argument, so the compiler cannot relate it to the slice — ran 1.10% faster than the plain loop, and a control pair of two identical loops differed by 1.45% in the same table. The check is a compare and a predicted branch, and the predictor gets it right every iteration.

How do I tell whether my loop has a bounds check?

Ask the compiler: go build -gcflags=-d=ssa/check_bce/debug=1 ./yourpackage. It prints a line per surviving check with the file and column, and silence means the prove pass removed them. It is one build, it needs no benchmark, and it answers the question the benchmark cannot answer clearly because the effect is smaller than the noise.

Should I ever write the hint?

Only where the compiler tells you a check survived, which in practice means a loop whose bound it cannot relate to the slice. Even then, measure: the surviving check in this file cost nothing detectable, so removing it buys nothing detectable either. The failure mode is a readability tax paid for a return nobody checked.

Nolan Keir

Systems-minded Go engineer

Nolan Keir writes about Go, backend engineering, and the systems behind production software. His work focuses on concurrency, runtime behavior, performance, tooling, and the trade-offs hidden behind clean abstractions. He prefers reproducible experiments and measurable behavior over rules of thumb. He writes at Gopheria.

More about the author

Arrow keys to move, Enter to open.