iterationperformanceallocation

Collect-then-iter round trip

Materializing an iterator into Vec just to iterate it again.

Why this looks tempting

It compiles, the borrow checker stops complaining, and the next .iter() is right there.

Why wrong

collect::<Vec<_>>() allocates and copies; the next .iter() walks that copy. You paid for a heap allocation, a bulk write, and a second pass over data you already had in a stream — usually to satisfy a borrow shape that wasn't actually required.

Fix

Keep the iterator chain end-to-end and call the consuming method directly (sum, for_each, fold, min_by_key). If you need to share the values, take the iterator by reference (&mut iter) or restructure so the source is owned. Allocate only when the result genuinely needs to outlive the chain.

Canonical alternative

performance/memory-optimization