Sub topic 15
Why iterator chains are zero-cost
This chapter explains why a chain such as filter, map and sum usually compiles to the same machine code as a hand-written loop. It also covers where that stops being true. It assumes you know closures, the Fn traits, generics with trait bounds, and the common adapters and consumers (map, filter, sum, collect).
What "zero-cost" means
"Zero-cost abstraction" has two parts. You don't pay for features you don't use. For features you do use, you couldn't hand-write the code any faster.
Zero-cost does not mean the chain does no work. It means the abstraction itself (iterator structs, closures, trait calls) adds no run-time overhead on top of the work a manual loop would do. The guarantee comes from three compiler mechanisms: monomorphization, inlining, and the absence of intermediate collections.
The same computation, two ways
Here is a loop and an iterator chain that compute the sum of the squares of the even numbers.
fn sum_loop(v: &[i32]) -> i32 {
let mut total = 0;
for i in 0..v.len() {
if v[i] % 2 == 0 {
total += v[i] * v[i];
}
}
total
}
fn sum_iter(v: &[i32]) -> i32 {
v.iter().filter(|&&x| x % 2 == 0).map(|&x| x * x).sum()
}
fn main() {
let data = [1, 2, 3, 4];
println!("{}", sum_loop(&data)); // 20
println!("{}", sum_iter(&data)); // 20
}In a release build (cargo build --release), these two functions typically produce equivalent machine code. The iterator version has an advantage. A slice iterator walks pointers and knows its own end, so it needs no bounds check. The indexed loop checks v[i] on every access. LLVM often removes those checks here, but the iterator form doesn't depend on it.
Mechanism 1: monomorphization
Every closure has its own anonymous type. Two closures with identical bodies still have different types. Every adapter is a generic struct wrapping the previous stage. The chain above has a type shaped like Map<Filter<slice::Iter<i32>, {closure}>, {closure}>.
When you call a generic function or method, rustc generates a specialized copy for each concrete type. This is monomorphization. The call to your closure is therefore a direct call to a known function. No lookup table is involved, and the compiler can see the closure's body.
A closure is also just a struct that holds its captures. A closure that captures nothing has size zero.
use std::mem::{size_of, size_of_val};
fn main() {
let n = 3i32;
let none = |x: i32| x + 1;
let by_move = move |x: i32| x + n;
let by_ref = |x: i32| x + n;
assert_eq!(size_of_val(&none), 0);
assert_eq!(size_of_val(&by_move), size_of::<i32>());
assert_eq!(size_of_val(&by_ref), size_of::<&i32>());
println!("{} {} {}", none(1), by_move(1), by_ref(1)); // 2 4 4
}The closure that captures nothing takes no memory. The move closure holds a copy of the i32. The borrowing closure holds a reference. There is no hidden heap allocation and no environment object.
Mechanism 2: inlining and fusion
Because each call is direct and the bodies are visible, LLVM can inline next for every adapter and inline each closure into it. After inlining, the layers of Option returns and match statements collapse into one loop with a few branches.
You can see the fusion at the language level. Each element passes through the whole chain before the next element starts. No stage processes the entire input first.
fn main() {
let v = vec![1, 2, 3];
let total: i32 = v
.iter()
.inspect(|x| println!("a {}", x))
.map(|x| x * 2)
.inspect(|x| println!("b {}", x))
.sum();
println!("total = {}", total);
}The output interleaves the stages: a 1, b 2, a 2, b 4, a 3, b 6, then total = 12. This is one pass over the data. The compiler turns that single pass into a single loop.
Mechanism 3: no intermediate collections
Adapters are lazy. filter does not produce a filtered Vec, and map does not produce a mapped one. The only allocation in a chain is the one you ask for at the end, such as collect. A hand-written equivalent that builds a temporary Vec at each stage would be slower, and the chain avoids that by construction.
Static versus dynamic dispatch
Zero-cost depends on the compiler knowing the concrete closure type. A generic parameter keeps that knowledge. A trait object removes it.
fn run_generic<F: Fn(i32) -> i32>(f: F, data: &[i32]) -> i32 {
data.iter().map(|&x| f(x)).sum()
}
fn run_dyn(f: &dyn Fn(i32) -> i32, data: &[i32]) -> i32 {
data.iter().map(|&x| f(x)).sum()
}
fn main() {
let data = [1, 2, 3];
let offset = 10;
println!("{}", run_generic(|x| x + offset, &data)); // 36
println!("{}", run_dyn(&|x| x + offset, &data)); // 36
}run_generic gets a copy specialized for the closure, so the call can be inlined. run_dyn calls through a vtable (a table of function pointers), once per element. That call is usually not inlined, and it blocks vectorization of the loop.
The cost of one indirect call is small. It matters in a hot inner loop over millions of items, and rarely elsewhere. Box<dyn Fn> has the same dispatch cost plus one heap allocation when you create it. Choose impl Fn or a generic parameter by default. Use dyn when you need to store different closures in one collection or hide a type.
Where the abstraction is not free
The guarantee covers the iterator machinery. It does not cover what you put into the chain.
| Situation | Cost | Why |
|---|---|---|
| `collect` into a `Vec` mid-pipeline | One allocation and copy per call | You asked for a real collection. |
| `Box<dyn Fn>` or `&dyn Iterator` in a hot loop | Indirect call per item | The compiler can't inline through a vtable. |
| Debug builds | Often many times slower | Without optimization, layers aren't inlined. |
| `f32` or `f64` `sum` | Usually not vectorized | Float addition isn't associative, so LLVM won't reorder it. |
| `clone()` inside `map` | The cost of the clone | Work you wrote is not overhead. |
| Long `chain` of iterators | Sometimes slower than two loops | The branch on which half is active can limit optimization. |
Some adapters have internal-iteration shortcuts. fold, for_each and sum drive the whole iterator in one call instead of calling next repeatedly. For adapters like chain, this lets the implementation run each half in its own tight loop. Prefer these consumers over a manual while let Some(x) = it.next() when you want the best code.
Reading the trade-offs
Monomorphization has a price. Each distinct closure type produces another copy of every generic function it passes through. Heavy use in large programs can increase compile time and binary size. Using dyn is one way to limit that, and the cost is the dispatch overhead above.
Early exit is also preserved. Consumers such as find, any and all stop as soon as the answer is known, just as a break would. A lazy chain with take(5) touches only five source items, so adding adapters doesn't force extra passes.
Exercise
A function takes f: &dyn Fn(i32) -> i32 and calls it inside data.iter().map(|&x| f(x)).sum(). Name two things the compiler cannot do because of the dyn, and state the change that restores them.
Show answer
It cannot inline the closure body into the loop, because the call goes through a vtable, and it usually cannot vectorize the loop for the same reason. Change the parameter to a generic F: Fn(i32) -> i32 (or impl Fn(i32) -> i32). Monomorphization then gives the compiler the concrete closure type, so it can inline and optimize.
Exercise
Why does v.iter().map(|x| x * 2).filter(|x| x % 3 == 0).sum::<i32>() not allocate, while inserting .collect::<Vec<_>>().into_iter() after map does?
Show answer
Adapters are lazy structs that pass one item at a time through the chain, so nothing is stored between stages. collect::<Vec<_>>() forces the whole map stage to run and store its results in a new heap-allocated vector, and into_iter then walks that vector. It adds an allocation, an extra pass and extra memory use for no benefit here.