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, no sign-in needed to watch.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;static void fill(int n) {
List<Integer> list = new ArrayList<>();
for (int i = 1; i <= n; i++)
list.add(i);
// Inside add:
// if (size == elementData.length) grow: allocate 1.5x, copy the items
// elementData[size++] = value;
}void fill(int n) {
vector<int> list;
for (int i = 1; i <= n; i++)
list.push_back(i);
// Inside push_back:
// if (size == capacity) grow: allocate double (libstdc++), move the items
// construct the new item at data[size++]
}items = []
for i in range(1, n + 1):
items.append(i)
# Inside append (CPython):
# if size == allocated: grow by about 1/8 extra, copy the item pointers
# ob_item[size] = value; size += 1Tips
- 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.