Why is an iterator chain usually as fast as a hand-written loop, and when is it slower?
Adapters are generic structs whose next is monomorphized and inlined: in release, filter().map().sum() becomes one loop with no bounds checks. It loses behind dyn Iterator, in debug builds, or with chunks where chunks_exact drops checks.
- Expecting each adapter to allocate a buffer or make its own pass over the data
- Benchmarking iterator chains in a debug build, where nothing is inlined
- Hiding a hot chain behind
Box<dyn Iterator>, which turns everynextinto an indirect call
- Why can
for_eachorfoldbeat aforloop over achainof two iterators? - How would you check that a chain was vectorized, for example in the online compiler explorer Godbolt?
Each adapter is a generic struct: Filter<Iter<'_, i64>, F> holds the inner iterator and the closure, and its next calls the inner next. A closure is not a function pointer but a type of its own, so after monomorphization the compiler sees the whole chain and inlines it into one loop. The adapters themselves allocate nothing and make no separate passes.
fn even_squares(v: &[i64]) -> i64 {
v.iter().filter(|x| *x % 2 == 0).map(|x| x * x).sum()
}
fn even_squares_loop(v: &[i64]) -> i64 {
let mut s = 0;
for x in v {
if x % 2 == 0 {
s += x * x;
}
}
s
}
fn even_squares_dyn(it: Box<dyn Iterator<Item = i64>>) -> i64 {
it.filter(|x| x % 2 == 0).map(|x| x * x).sum()
}
fn xor_ends(v: &[u32]) -> u32 {
// chunks(4) would keep a bounds check on c[3]: its last chunk may be shorter
v.chunks_exact(4).map(|c| c[0] ^ c[3]).sum()
}
fn main() {
let v: Vec<i64> = (1..=10).collect();
let a = even_squares(&v);
let b = even_squares_loop(&v);
let c = even_squares_dyn(Box::new(v.clone().into_iter()));
let w: Vec<u32> = (1..=8).collect();
println!("{a} {b} {c} {}", xor_ends(&w)); // 220 220 220 18
}What the rustc 1.99.1 assembly shows with -C opt-level=3 on x86-64:
even_squaresandeven_squares_loopbecome loops with no function calls and no bounds checks. They are not byte-identical — the chain is unrolled by two elements, the loop by four — but they are the same kind of code.- A
for i in 0..nloop overv[i], wherenis unrelated tov.len(), keeps a call topanic_bounds_check. A slice iterator needs no such check: it knows where the end is. even_squares_dyncallsnextthrough the method table for every element: the compiler cannot see which iterator sits in theBox, so it can inline nothing.chunks(4)keeps a bounds check onc[3], whilechunks_exact(4)drops it: every chunk's length is known, and the leftover is available throughremainder().
Two more cases where a chain loses. A debug build inlines nothing, so every next of every adapter is a real function call; compare speed in release only, for example with the criterion crate. An external for loop over chain or flat_map checks on every element which half is active; for_each, fold and sum use internal iteration, which walks the halves in two simple loops and is often faster. Side effects in a closure, such as println!, block vectorization — but exactly as they would in a hand-written loop.