Sub topic 15
Why iterator chains are zero-cost
This chapter assumes you can read iterator chains with map, filter and sum, and that you know generics and trait bounds. It explains why a chain costs about the same as a hand-written loop. It also covers where that stops being true.
What "zero-cost" means
Zero-cost means two things. You don't pay at run time for the abstraction. If you wrote the loop by hand, you couldn't produce faster code. Rust doesn't promise that every chain is free. It promises that the chain adds no overhead you could have avoided.
The two examples
Here is the same computation written twice. Both sum the squares of the even numbers in a slice.
fn sum_sq_loop(v: &[i32]) -> i32 {
let mut total = 0;
for i in 0..v.len() {
let x = v[i];
if x % 2 == 0 {
total += x * x;
}
}
total
}
fn sum_sq_iter(v: &[i32]) -> i32 {
v.iter().filter(|&&x| x % 2 == 0).map(|&x| x * x).sum()
}
fn main() {
let data = [1, 2, 3, 4, 5, 6];
println!("{}", sum_sq_loop(&data)); // 56
println!("{}", sum_sq_iter(&data)); // 56
}In release builds, the optimizer usually produces equivalent machine code for both. The iterator version often does better, because iter() already knows the slice length, so the compiler can drop the per-element bounds check that v[i] needs.
How the compiler gets there
Three mechanisms combine.
- Every closure has its own unique type. The
filterclosure and themapclosure are different anonymous types. Their code is known at compile time. - Generics are monomorphized.
Filter<Iter<i32>, F>is generated for that exactF. There is no virtual call to look up. - Adapters are plain structs on the stack.
mapandfilterhold the previous iterator and a closure. They allocate nothing. Smallnextmethods get inlined, and the nested calls collapse into one loop.
Correction: the diagram must use the required fence format. Here it is.
Where the cost comes back
The guarantee has limits.
| Situation | Cost |
|---|---|
| Debug build (`cargo run` without `--release`) | Little inlining, so chains can be much slower than loops |
| `Box<dyn Fn>` or `&dyn Fn` | One dynamic call per use, and it blocks inlining |
| `collect()` into a `Vec` | One or more heap allocations. Skip it when you can keep chaining |
| Cloning inside a closure | The clone itself, which is your cost, not the iterator's |
Practical rules
- Prefer generics (
F: Fn(i32) -> i32orimpl Fn) over trait objects in hot paths. - Avoid intermediate
collect()calls. Chain adapters and consume once. - Write the readable chain first. Measure before you rewrite it as a loop.
Exercise
A function takes f: Box<dyn Fn(i32) -> i32> and calls it on every element of a large slice inside a for loop. Name two reasons it may be slower than the same function taking F: Fn(i32) -> i32.
Show answer
The boxed closure is called through a vtable, so each call is dynamic dispatch. The compiler also cannot inline the closure body into the loop, so it loses optimizations such as merging the loop and removing bounds checks. The box also costs a heap allocation when it is created.