Bounds Checks in Rust and When the Optimizer Removes Them
Every v[i] checks the index. In many loops the optimizer proves the check unnecessary and removes it. Learn when that happens, how to help it and why unchecked indexing is rarely worth it.

A common worry about Rust's speed is the check on every array access. The check exists, it is cheap, and in many loops it is not there at all because the compiler removed it. The skill is knowing which loops lose it and what to write when one does not. This post shows three loops and what the optimizer does with each. It goes with the iterator comparison in iterator chains versus loops in the performance cluster.
Rust 1.90, edition 2024. Assembly inspected with cargo asm or the Compiler Explorer.
Three loops
pub fn sum_a(v: &[u32]) -> u32 {
let mut s = 0;
for i in 0..v.len() {
s += v[i];
}
s
}
pub fn sum_b(v: &[u32], n: usize) -> u32 {
let mut s = 0;
for i in 0..n {
s += v[i];
}
s
}
pub fn sum_c(v: &[u32], n: usize) -> u32 {
let v = &v[..n];
let mut s = 0;
for i in 0..n {
s += v[i];
}
s
}**sum_a**: the loop runs to v.len(), so every index is in range and the compiler drops the check.
**sum_b**: n could exceed v.len(), so each v[i] keeps its check, and the loop can panic partway through. This version typically does not vectorize.
**sum_c**: &v[..n] checks once, up front. After it, the compiler knows v.len() == n and the loop body indexes freely. One check replaces n of them.
If you want to confirm on your toolchain, compile with --release and look for a call to core::panicking::panic_bounds_check inside the loop body.
The cheap fixes
- Iterate directly:
for x in vorv.iter().sum(). - Slice before the loop, as in
sum_c. - For several parallel slices, take them to the same length first:
let n = a.len().min(b.len());
let (a, b) = (&a[..n], &b[..n]);
for i in 0..n {
out[i] = a[i] + b[i];
}- Use
ziporchunks_exact, which carry the length in the type.
Last resort
// SAFETY: i < v.len() was checked by the loop condition above.
let x = unsafe { *v.get_unchecked(i) };This removes the check and makes a wrong index undefined behavior instead of a panic. We rarely see it improve a program once the safe restructurings above are applied. If you use it, follow safety comments and test under Miri (using Miri).
Is it worth the effort
A well-predicted branch that is never taken costs close to nothing on a modern CPU. The real cost comes from blocking optimizations like vectorization, which treats a possible panic in the middle of the loop as a side effect it must preserve. So: do not hand-optimize bounds checks in code that is not a numeric hot loop. Profile first, as in profiling Rust programs.
Limits
The optimizer's behavior changes between compiler versions. A loop that was check-free in one release can regress in another, which is a reason to keep a benchmark. The Rust Performance Book describes the technique under bounds checks.


