How to avoid unnecessary allocations

Pre-allocate collection capacity and use iterators to prevent creating temporary data structures that waste memory.

Avoid unnecessary allocations by pre-allocating collection capacity and using iterators instead of intermediate collections. Use Vec::with_capacity to reserve memory upfront and prefer iterator methods like map and filter over creating temporary vectors.

let mut v = Vec::with_capacity(100);
for item in data.iter().filter(|x| *x > 0).map(|x| x * 2) {
    v.push(item);
}