Collections & Iterators Best Practices
How to Use This List
- Profile before micro-optimizing iterators.
- Enable clippy
needless_collectanditer_overeager_cloned.
A - Collection Choice
- Default to
Vecfor sequences. Specialized containers when measured need. -
HashMapfor speed,BTreeMapfor order/range. Document choice. - Avoid
LinkedListunless proven.VecDequeusually wins. - Reserve capacity when size known.
with_capacityreduces realloc. - Use
entryAPI for map updates. Avoid double lookup.
B - Iterators
- Prefer iterators over manual index loops.
enumeratewhen index needed. - Avoid needless
collectbetween adapters. Chain lazily. - Use
try_collect/ Result collect for fallible maps. Short-circuit errors. - Borrow with
iter()unless ownership needed.into_iterconsumes. - Bound infinite iterators with
take. Prevent hangs.
C - Allocation
- Reuse buffers in hot loops.
clear+ reuseVec. - Prefer
&strkeys only when lifetimes allow. OwnedStringkeys common. - Consider
SmallVecfor usually-small lists. Fewer heap hits. - Profile allocator on hot paths.
dhat,heaptrack. - Do not premature
shrink_to_fiteverywhere. Only after spikes.
D - Correctness
- Do not mutate vec during non-adapter iteration. Use
retain,drain. - Handle empty reduce/fold. Provide seed or
Option. - Document sort stability requirements.
sortvssort_unstable. - Test equality independent of map order. Sort keys or use
BTreeMapin tests. - Use typed
collectexplicitly in complex chains. Aid inference.
FAQs
rayon when?
CPU-bound parallel over large data.itertools?
Extra adapters - dep budget.ahash?
Faster maps - evaluate security tradeoffs.sort in prod?
Unstable often faster - document.smallstr?
Inline strings for map keys.no_std?
hashbrown + alloc.serde maps?
Object vs vec of pairs.bench?
criterion iterator vs loop.polars?
Columnar when analytics scale.next?
Closures powering iterators.Related
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.