Interview frequency: …
Short answer
It prevents repeated internal array allocations and copying data on the Heap each time the collection grows beyond its current size.
Explanation
List<T> starts with a small internal array (for example, four elements). Adding a fifth element creates a new array of double the size (eight), copies all elements, and leaves the old array for the GC. Adding 10,000 elements this way repeats the costly process 12 times. new List<T>(10000) allocates the required array once, avoiding extra copies and maximizing speed.
Code example
// Preallocate the capacity
var list = new List<Customer>(expectedCount);
var dict = new Dictionary<int, Customer>(expectedCount);Common mistakes
- Creating lists and dictionaries without initial capacity when reading a known-size dataset from a database.