Pencil trace: append and insert on a tiny slice
There is no code here. In this step you watch what a slice does to its elements when you append or insert — on a small example you can check with a pencil. In the next step you measure the same thing for a thousand items.
How we count
- copied — how many elements
appendhad to copy into a new array, because the old one was full (len == cap); - shifted — how many elements moved by one slot to open a gap for an insert.
append, nine times in a row
Start from an empty slice and append one Item nine times. After each one —
what len and cap are, and whether anything was copied:
append len cap copied
1 1 1 0 new array
2 2 2 1 new array, 1 element moved
3 3 4 2 new array
4 4 4 —
5 5 8 4 new array
6 6 8 —
7 7 8 —
8 8 8 —
9 9 18 8 new array
total: 15 copies in 9 appends
Look at when it copies: only when len has reached cap. Every other time
append just writes into a free slot and costs nothing.
Inserting in the middle
You have five items and want to insert X at position 2. There is no room
between Bangos and Ciklas — the elements sit back to back. So everything
from that position on moves one slot to the right, starting from the end:
start [Aidas Bangos Ciklas Dūmai Ežeras · ]
Ežeras → 5 [Aidas Bangos Ciklas Dūmai · Ežeras ] 1
Dūmai → 4 [Aidas Bangos Ciklas · Dūmai Ežeras ] 2
Ciklas → 3 [Aidas Bangos · Ciklas Dūmai Ežeras ] 3
write X [Aidas Bangos X Ciklas Dūmai Ežeras ] shifted: 3
The same operation at three positions, on the same five elements:
insert X at shifted
0 (front) 5
2 (middle) 3
5 (end) 0 that is just append
Three observations. The following steps are built out of nothing else.
1. append usually costs nothing, but sometimes it costs everything. Of
nine appends, four were "free", and the other five copied 0, 1, 2, 4 and 8
elements. The expensive copy gets rarer, but bigger.
2. Capacity does not always double. 1, 2, 4, 4, 8 — at the start it does. But the ninth append gave 18, not 16. Why — in the step after this one.
3. The cost of an insert is n − position. The nearer the front, the more
elements get pushed; at the end, none. Inserting in the middle is O(n) not
because finding the spot is slow, but because the gap has to be pushed open.
What comes next
In the next step you write code that does the same append observation for a
thousand items, and you see what "amortized" looks like.