Sub topic 8
Iterator chains instead of intermediate collections
This chapter assumes you know ownership and borrowing, can read closures, and have used Vec, String, and basic iterator adapters such as map and filter. It also assumes you have seen the counting allocator from the measuring chapter. You will learn to spot collect() calls that only exist to feed the next step, replace them with a lazy chain, and recognize when collecting is the right choice.
Why an intermediate collection costs something
Calling collect::<Vec<_>>() asks the allocator for a heap buffer. If the iterator cannot report its exact length, the Vec may also grow and reallocate while it fills. Every element is written into that buffer, then read back by the next step, then the buffer is freed.
An iterator chain works differently. Adapters such as map, filter, take, and zip are small structs that hold the previous iterator and a closure. Nothing is stored. Each call to next() pulls one item through the whole chain, and a consuming method such as count, sum, or for_each drives it. The adapter structs live on the stack, so the chain allocates nothing unless one of its own steps does.
The basic rewrite
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 = "iterators are lazy and allocation free until consumed";
println!("{}", count_long_words(text));
println!("{}", count_long_words_collected(text));
}Both print 3. The second function allocates a Vec<&str> that the first never builds. The elements are only &str slices, so no string data is copied, but the vector buffer is still a heap allocation, and it grows as words arrive.
The collected version is a common pattern in code written step by step. A line like let words: Vec<_> = ...collect(); often exists only because the author wanted a name for the intermediate result. A named binding does not require a collection. You can bind the iterator itself:
fn main() {
let text = "a short line with some longer words inside";
let words = text.split_whitespace();
let long = words.filter(|w| w.len() > 5);
println!("{}", long.count());
}This is still lazy. Nothing runs until count() consumes long.
Fold the work into the consumer
Many collect-then-process patterns can be replaced by a consuming method that does the second step directly.
| Instead of | Use | Why | Column | Column |
|---|---|---|---|---|
| `v.collect::<Vec<_>>().len()` | `.count()` | Counts without storing | ||
| `v.collect::<Vec<_>>().iter().sum()` | `.sum()` | Adds as items arrive | ||
| `v.collect::<Vec<_>>().is_empty()` | `.next().is_none()` | Stops after one item | ||
| `v.collect::<Vec<_>>()[0]` | `.next()` | Produces one item only | ||
| `v.collect::<Vec<_>>().contains(&x)` | `.any(\ | i\ | i == x)` | Short-circuits |
Consumers like any, all, find, and next stop early. A collected version always does the full pass first, so laziness can save time as well as memory.
Fallible parsing is another good case. Result implements Sum, so a chain can stop at the first error without storing the parsed numbers:
use std::num::ParseIntError;
fn sum_numbers(input: &str) -> Result<i64, ParseIntError> {
input.split(',').map(|s| s.trim().parse::<i64>()).sum()
}
fn main() {
println!("{:?}", sum_numbers("1, 2, 3"));
println!("{:?}", sum_numbers("1, x, 3").is_err());
}The first call prints Ok(6) and the second prints true. Similarly, collect::<Result<Vec<_>, _>>() is the right tool only when you need the values afterward.
Returning iterators from functions
A function that returns Vec<T> forces every caller to pay for the allocation, even if the caller only counts or loops. Returning impl Iterator leaves that choice to the caller:
fn long_words<'a>(text: &'a str, min: usize) -> impl Iterator<Item = &'a str> + 'a {
text.split_whitespace().filter(move |w| w.len() > min)
}
fn main() {
let text = "borrowing keeps allocation counts low";
for w in long_words(text, 6) {
println!("{w}");
}
let owned: Vec<&str> = long_words(text, 6).collect();
println!("{}", owned.len());
}The move keyword on the closure copies min into it, so the returned iterator does not borrow a local variable. The caller who needs a Vec can still call collect(), and the caller who does not need one pays nothing.
Trade-offs of returning `impl Iterator`
- The concrete type is hidden, so you cannot name it in a struct field without generics or
Box<dyn Iterator>. Boxing brings back an allocation, so use it only when you must return different iterator types from different branches. - The iterator borrows its input, so the input must outlive it.
- Callers cannot index it or call
len()unless the type implementsExactSizeIteratorand you promise that in the signature.
When collecting is the right choice
Laziness is not always better. Collect when you need any of the following:
- Sorting, deduplicating, or random access. These need all elements in memory.
- More than one pass. Re-running a chain repeats its work, and a side-effecting or expensive closure runs again.
- Ownership past the borrow. If the source is a temporary, you may need to copy data out before the source goes away.
- Simpler code on a cold path. A collect that runs once at startup is not worth a harder-to-read chain.
For example, a median needs a sorted buffer, so one collect is correct:
fn median_len(text: &str) -> Option<usize> {
let mut lens: Vec<usize> = text.split_whitespace().map(str::len).collect();
if lens.is_empty() {
return None;
}
lens.sort_unstable();
Some(lens[lens.len() / 2])
}
fn main() {
println!("{:?}", median_len("one three five seven"));
}The collect here is the only allocation, and it is necessary.
Collecting well when you must
When you do collect, help the Vec size itself. collect calls size_hint() on the iterator and reserves the lower bound up front. Some adapters preserve an exact hint and some do not:
fn main() {
let v = vec![1, 2, 3, 4];
println!("{:?}", v.iter().map(|x| x * 2).size_hint());
println!("{:?}", v.iter().filter(|x| **x > 1).size_hint());
}This prints (4, Some(4)) and then (0, Some(4)). map keeps the exact length, so collect allocates once. filter cannot know how many items pass, so its lower bound is 0 and the Vec may reallocate as it grows. If you know a good estimate, reserve it yourself and use extend:
fn evens_into(out: &mut Vec<u32>, input: &[u32]) {
out.clear();
out.reserve(input.len() / 2);
out.extend(input.iter().copied().filter(|n| n % 2 == 0));
}
fn main() {
let mut buf = Vec::new();
evens_into(&mut buf, &[1, 2, 3, 4, 5, 6]);
println!("{:?}", buf);
evens_into(&mut buf, &[10, 11, 12]);
println!("{:?}", buf);
}Because evens_into takes &mut Vec<u32>, a loop can reuse one buffer across calls, which combines this chapter with the buffer-reuse chapter. The second call does not allocate if the first call's capacity is enough.
Building strings without a middle Vec
A frequent version of the intermediate-collection problem is map(...).collect::<Vec<String>>().join(" "). It allocates one String per word, one Vec to hold them, and one final String. Writing straight into the output avoids the first two:
fn shout(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for (i, w) in text.split_whitespace().enumerate() {
if i > 0 {
out.push(' ');
}
out.extend(w.chars().flat_map(char::to_uppercase));
}
out
}
fn main() {
println!("{}", shout("lazy chains save memory"));
}The output is LAZY CHAINS SAVE MEMORY. Only the single output String is allocated. Here String::with_capacity(text.len()) is a good guess, but uppercasing some characters can lengthen the text, so the string may still grow once in rare cases. That is acceptable, since capacity is a hint and the string stays correct.
Common mistakes
- Collecting to call
.iter(). If the next step is.iter(),.into_iter(), or aforloop, you can usually skip the collect. - Forgetting that adapters are lazy.
v.iter().map(|x| println!("{x}"));does nothing and the compiler warns that the iterator is unused. Usefor_eachor aforloop for side effects. - Allocating inside the closure. A lazy chain can still allocate per item.
.map(|w| w.to_string())or.map(|w| format!("{w}!"))creates oneStringper element. Check closures for hidden allocations with the counting allocator. - Assuming a chain is always faster. Removing a
Vecremoves an allocation, but speed depends on the rest of the work. Measure before and after.
Exercises
Exercise
The function below allocates a Vec on every call. Rewrite it so it allocates nothing, and say which consuming method replaces the collect. fn haserrorline(log: &str) -> bool { let lines: Vec<&str> = log.lines().collect(); lines.iter().any(|l| l.starts_with("ERROR")) }
Show answer
Remove the collect and call any directly on the lines iterator: log.lines().any(|l| l.starts_with("ERROR")). The any method consumes the chain one line at a time, needs no buffer, and stops at the first match, so it also avoids reading the rest of the log.
Exercise
A colleague writes names.iter().map(|n| n.to_uppercase()).collect::<Vec<String>>().join(", ") in a loop that runs a million times. Name the allocations it performs per call, and describe a lower-allocation approach.
Show answer
It allocates one String per name from touppercase, one Vec to hold those Strings, and one final String from join. A lower-allocation approach is to create one output String (reused across iterations with clear, or sized with withcapacity), then loop over the names, push a separator when needed, and extend the output with the uppercased characters, as in the shout example. That leaves at most one allocation per call, or none when the buffer is reused.