Why Most Appends Are Cheap

A growing array can have occasional expensive appends even when the total number of copies over a long sequence is small.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace five appends
  2. Check a different guarantee
  3. Account for each resize across a whole sequence
  4. Keep worst-case latency separate

Trace five appends

Starting at capacity one and doubling, inserts two, three, and five copy one, two, and four earlier elements. Inserts one and four require no resize in this scheme. The resize copies sum to seven. Dynamic array growth explains how the capacities keep the sum linear in the number of appends.

Check a different guarantee

A limit on individual response time cares that the fifth insert copied four elements. A total-work bound describes the full run. Amortized time versus latency develops this distinction.[1]

Account for each resize across a whole sequence

Start a dynamic array at capacity one and double on overflow. Appending through size nine copies one existing item at the first growth, then two, four and eight. The later growth steps dominate the earlier ones, which is why the aggregate copy cost stays linear. See growing a hash table.

Append count reaching 2: copy 1
Reaching 3: copy 2
Reaching 5: copy 4
Reaching 9: copy 8
Total copies 15, plus 9 new writes

Keep worst-case latency separate

An append triggering growth can be linear in the current size. Amortized constant time describes the sequence, not a latency bound for every call. With growth by a fixed increment, the copy costs instead form an arithmetic series and their sum grows faster.

References

  1. Jeff Erickson, Algorithms ↩