# 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.

- Published: 2026-11-22
- Tags: compiler, performance, benchmarking
- Source: https://gopheria.com/blog/bounds-check-elimination-measured/
- Language: en-US
- Author: Nolan Keir

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

```text
$ 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/`](https://github.com/CognatePress/experiments.gopheria.com/tree/main/bce).

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

```go
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](/blog/benchstat-or-it-didnt-happen/). 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

```text
$ go test -run=^$ -bench='Warmup|Sum' -benchmem -count=10 ./bce |
    grep -v Warmup | benchstat -row /n -col /form -
```

```text
        │   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](/blog/benchstat-or-it-didnt-happen/) 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.

:::note
This is a sum over `uint64` with no work in the body, which is the friendliest
possible case for the predictor and the least friendly for showing a per-
iteration cost. A loop with unpredictable early exits would give the branch
predictor something to get wrong, and I have not measured that one.
:::

## Ask the compiler instead

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

```bash
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](/blog/the-inlining-budget-counted/)
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.
