Sub topic 3
Iterator Chains and Allocation-Aware Data Design
Assume you know Rust ownership, borrowing, lifetimes, Vec, Box, and basic iterators. This chapter focuses on choosing data structures and APIs that avoid allocations when the workload does not need them.
Prefer lazy iterator chains
Iterator adapters such as filter and map are lazy. They process items only when a consumer, such as count or sum, requests them. Calling collect creates an intermediate collection and may allocate.
fn count_long_words(text: &str) -> usize {
text.split_whitespace()
.filter(|word| word.len() > 5)
.count()
}
fn count_long_words_with_collection(text: &str) -> usize {
let words: Vec<&str> = text.split_whitespace().collect();
words.iter().filter(|word| word.len() > 5).count()
}
fn main() {
let text = "Rust avoids many unnecessary memory allocations";
println!("{}", count_long_words(text));
println!("{}", count_long_words_with_collection(text));
}The first function does not store every word. Use collect when you need ownership, repeated traversal, indexing, or a collection that outlives the iterator.
Choose storage for the workload
SmallVec stores a small number of values inline, usually inside the collection object, and moves to the heap only after that inline capacity is exceeded. It is useful when most collections remain small, but it adds a dependency and more complex behavior.
Box<T> gives one heap allocation and stable ownership. Avoid it merely to return a value or hide a type. Box<dyn Trait> also adds dynamic dispatch and usually an allocation. Use it when runtime-selected types or recursive structures require it. Otherwise, generics and enums often avoid both costs.
| Type | Typical reason to use it | Allocation behavior |
|---|---|---|
| `Vec<T>` | Variable-sized owned data | Heap allocation when nonempty |
| `SmallVec<[T; N]>` | Usually-small collections | Inline up to `N`, then heap |
| `Box<T>` | Indirection or stable address | One heap allocation |
| `Rc<T>` / `Arc<T>` | Shared ownership | Allocation plus reference-count metadata |
Box<str> can store a compact, owned string after its final length is known. Rc<str> shares immutable data within one thread. Arc<str> supports sharing across threads, with atomic reference-counting costs.
Use arenas and zero-copy designs deliberately
An arena allocates many objects from larger regions and releases them together. This can reduce per-object allocation overhead when objects share a lifetime. It prevents individual early deallocation, so it is a poor fit for independently long-lived objects.
Zero-copy parsing keeps slices such as &str or &[u8] pointing into the input buffer. This avoids copying fields, but the input must remain alive and unchanged.
Change the allocator only after measuring
A global allocator affects the whole program. A different allocator can help allocation-heavy workloads, but it cannot remove allocations caused by collect, cloning, or poor ownership design. Measure allocation counts and runtime first, then benchmark a representative workload.
Exercise
Why can replacing collect with a direct iterator consumer reduce allocations?
Show answer
The consumer can process each item as it arrives, so no intermediate collection or backing allocation is required.