Sub topic 8
Iterator Chains Instead of Intermediate Collections
This chapter assumes you know Rust ownership and borrowing, can use Vec and String, and are comfortable with closures and basic iterator methods such as map and filter.
The working model
Iterator adapters like map, filter and take are lazy. Calling them allocates nothing and does no work. Work happens only when a consuming method such as count, sum, fold, for_each or collect pulls items through the chain. Each item passes through every stage before the next item starts.
A call to collect::<Vec<_>>() in the middle of a pipeline breaks this model. It runs the first stage to completion and stores every item in a new heap buffer. The next stage then reads that buffer. You pay for the allocation, the possible regrowth, and the extra memory traffic.
Comparing the two shapes
Here are two functions that return the same result:
fn count_long_words(text: &str) -> usize {
text.split_whitespace().filter(|w| w.len() > 5).count()
}
fn count_long_words_collected(text: &str) -> usize {
let words: Vec<&str> = text.split_whitespace().collect();
words.iter().filter(|w| w.len() > 5).count()
}
fn main() {
let text = "the quick brown foxes jumped over lazy sleeping dogs";
println!("{}", count_long_words(text));
println!("{}", count_long_words_collected(text));
}Both print 4. The first version never stores the words. Each word is produced, tested and counted, then dropped. The second version allocates a Vec<&str>, which may reallocate several times as it grows. It stores one 16-byte slice per word, even though only the count is needed.
Rewriting a collect-then-loop pattern
The same problem shows up with owned data. This version builds a temporary Vec<u64> of squares and then sums it:
fn sum_even_squares_slow(values: &[u64]) -> u64 {
let squares: Vec<u64> = values
.iter()
.filter(|v| **v % 2 == 0)
.map(|v| v * v)
.collect();
squares.iter().sum()
}
fn sum_even_squares(values: &[u64]) -> u64 {
values
.iter()
.filter(|v| **v % 2 == 0)
.map(|v| v * v)
.sum()
}
fn main() {
let data = [1, 2, 3, 4, 5, 6];
println!("{} {}", sum_even_squares_slow(&data), sum_even_squares(&data));
}Both print 56. The fix is to delete the collect and let the consumer, here sum, end the chain.
When collecting is the right call
Some collect calls are necessary:
- You need to iterate the items more than once, and recomputing them is costlier than storing them.
- You need random access, sorting, or the length before you start. A plain iterator gives none of these.
- The iterator borrows from something that will not live long enough, so the items must be owned.
- The result is the function's return value and the caller needs a concrete collection.
If you must collect, size the buffer well. Iterators with an accurate size_hint, such as ranges and slice iterators, let collect allocate once. A filter in the chain makes the lower bound zero, so the Vec may regrow.
Common errors
- Collecting to call
.len(). Use.count()on the iterator instead. - Collecting to check for a match. Use
any,all,findorposition. These also stop at the first decisive item. - Returning
Vecfrom a helper that callers only loop over. Returnimpl Iterator<Item = T> + '_so the caller decides whether to collect. - Collecting in a hot loop for
join. Write into oneStringwithwrite!, or use a crate such asitertoolsfor joining without a temporaryVec.
Measure before and after, as in the earlier chapter on counting allocations. A chain is not always faster, but the allocation count should drop.
Exercise
A function builds let names: Vec<String> = users.iter().map(|u| u.name.to_uppercase()).collect(); and then only checks names.iter().any(|n| n == "ADMIN"). How would you remove the intermediate collection, and what allocation remains?
Show answer
Drop the collect and end the chain with any: users.iter().map(|u| u.name.to_uppercase()).any(|n| n == "ADMIN"). This removes the Vec<String> and stops at the first match. Each to_uppercase call still allocates a temporary String. To remove those too, compare without allocating, for example with u.name.eq_ignore_ascii_case("admin") if ASCII comparison is acceptable.