Pre-allocate vector memory with Vec::with_capacity to prevent performance penalties from repeated reallocations.
Use Vec::with_capacity(n) to pre-allocate memory for a known number of elements, avoiding costly reallocations during growth.
let size = 100;
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id));
}
This reserves space for size items upfront, so push operations inside the loop do not trigger memory reallocation or data copying.
Think of this like reserving a table for a specific number of guests before they arrive. Instead of constantly moving everyone to a bigger table as more people show up, you get the right size table immediately. This saves time and effort when you know exactly how many items you need to store.