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);
}
Think of memory like a warehouse; unnecessary allocations are like renting a new truck for every single box you move. Pre-allocating is like renting one big truck that fits everything, while iterators let you move boxes directly without stopping to pack them into temporary boxes first.