13.5 Performance Considerations

Rust iterators often compile to the same machine instructions as traditional loops in C, thanks to inlining and other optimizations. Iterator abstractions are typically zero-cost.

13.5.1 Lazy Evaluation

Adapter methods (like map() and filter()) are lazy. They do no actual work until the iterator is consumed:

fn main() {
    let numbers = vec![1, 2, 3, 4, 5];
    let mut iter = numbers.iter().map(|x| x * 2).filter(|x| *x > 5);
    // No computation happens yet.

    assert_eq!(iter.next(), Some(6)); // Computation starts here.
    assert_eq!(iter.next(), Some(8));
    assert_eq!(iter.next(), Some(10));
    assert_eq!(iter.next(), None);
}

13.5.2 Zero-Cost Abstractions

The Rust compiler aggressively optimizes iterator chains, so you rarely pay a performance penalty for writing high-level iterator code:

fn main() {
    let numbers = vec![1, 2, 3, 4, 5];

    // Using iterator methods
    let total: i32 = numbers.iter().map(|x| x * 2).sum();
    println!("Total: {}", total); // 30

    // Equivalent manual loop
    let mut total_manual = 0;
    for x in &numbers {
        total_manual += x * 2;
    }
    println!("Manual total: {}", total_manual); // 30
}