13.5 Performance Considerations
13.5.1 Iterator Laziness
Lazy Evaluation delays computation until necessary.
Example:
fn main() { let numbers = vec![1, 2, 3, 4, 5]; let mut iter = numbers.iter().map(|x| x * 2).filter(|x| *x > 5); // no action assert_eq!(iter.next(), Some(6)); // processing 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
Rust's iterators are designed to have no runtime overhead compared to manual implementations.
Iterator vs. Loop:
Using Iterators:
fn main() { let numbers = vec![1, 2, 3, 4, 5]; let total: i32 = numbers.iter().map(|x| x * 2).sum(); println!("Total: {}", total); // Output: Total: 30 }
Using a Loop:
fn main() { let numbers = vec![1, 2, 3, 4, 5]; let mut total = 0; for x in &numbers { total += x * 2; } println!("Total: {}", total); // Output: Total: 30 }