How List<T> grows
A List<T> is an array with spare room. When the room runs out it allocates an array twice as big and copies everything across.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
Most Add calls just write into the next free slot. Occasionally the array is full and everything is copied to a bigger one. Because the size doubles, those expensive copies become rarer as the list grows, and the average cost per Add stays constant.
Code
var list = new List<int>();
for (int i = 1; i <= n; i++)
list.Add(i);
// Inside Add:
// if (Count == Capacity) grow: allocate double, copy the items
// items[Count++] = value;Tips
- Capacity goes 0, 4, 8, 16, 32 and so on.
- The same doubling trick is behind StringBuilder, Stack<T>, Queue<T> and Dictionary.
In the .NET library
If you know the size in advance, new List<int>(n) allocates once and skips every resize. list.Capacity and list.Count let you watch this happen.