Dynamic Tables: Expansion
Python lists, C++ vectors, Java ArrayLists and hash tables all keep their elements in one contiguous block of memory that must be reallocated when it fills up. How big should the new block be? The Dynamic Arrays and Doubling lesson answered "twice as big" and counted the copies. This lesson analyses the same structure with all three amortized methods, so that you can see them side by side on the problem they were invented for, and then asks what other growth factors cost.
The model
A dynamic table stores items in an allocated block of slots, with . Its load factor is (and for the empty table with ). Inserting into a table with a free slot costs 1. Inserting into a full table first allocates a block twice as large, copies the old items into it (cost 1 each), frees the old block, and then inserts (cost 1).
TABLE-INSERT(T, x)
1 if T.size == 0
2 allocate T.table with 1 slot; T.size = 1
3 if T.num == T.size // full: expand
4 allocate new-table with 2 * T.size slots
5 copy all items of T.table into new-table // T.num elementary insertions
6 free T.table; T.table = new-table; T.size = 2 * T.size
7 insert x into T.table // one elementary insertion
8 T.num = T.num + 1The cost of insertion is if is a power of 2 (the table was full with items and they are all copied), and otherwise. The worst single insertion is .
Aggregate analysis
The expansions happen at insertions , copying items. So the total cost of insertions is
The amortized cost per insertion is less than 3.
Accounting analysis
Charge 3 per insertion. One unit pays for the insertion itself. Right after an expansion to size , the table holds items and no credit. The next insertions each leave 2 units of credit: one on the item just inserted and one on an item from the older half, which has none yet. By the time the table is full again, all items carry one unit, enough to pay for copying all of them in the next expansion.
Potential analysis
The credit picture suggests the potential: zero right after an expansion, rising by 2 with each insertion, and equal to when the table is full. That is
It is 0 right after an expansion (), equal to when full, and never negative since the table is always at least half full (from the first expansion on; the empty table has ).
- No expansion: , rises by 1, unchanged: .
- Expansion from size (full, ) to : , and goes from to , so .
Every insertion has amortized cost exactly 3 (the very first one, which allocates the first slot, has ).
def simulate(n, verbose=False):
num = size = 0
phi = lambda: 2 * num - size
total = 0
for i in range(1, n + 1):
before = phi()
cost = 0
if size == 0:
size = 1
if num == size:
cost += num # copy every item
size *= 2
cost += 1 # the insertion itself
num += 1
total += cost
if verbose:
print(f"insert {i:2}: size {size:2}, actual cost {cost:2}, Phi {before:2} -> {phi():2}, amortized {cost + phi() - before}")
return total
simulate(10, verbose=True)
for n in [10, 1000, 10 ** 6]:
t = simulate(n)
print(f"n = {n:7}: total cost {t:7}, per insertion {t / n:.3f}")insert 1: size 1, actual cost 1, Phi 0 -> 1, amortized 2
insert 2: size 2, actual cost 2, Phi 1 -> 2, amortized 3
insert 3: size 4, actual cost 3, Phi 2 -> 2, amortized 3
insert 4: size 4, actual cost 1, Phi 2 -> 4, amortized 3
insert 5: size 8, actual cost 5, Phi 4 -> 2, amortized 3
insert 6: size 8, actual cost 1, Phi 2 -> 4, amortized 3
insert 7: size 8, actual cost 1, Phi 4 -> 6, amortized 3
insert 8: size 8, actual cost 1, Phi 6 -> 8, amortized 3
insert 9: size 16, actual cost 9, Phi 8 -> 2, amortized 3
insert 10: size 16, actual cost 1, Phi 2 -> 4, amortized 3
n = 10: total cost 25, per insertion 2.500
n = 1000: total cost 2023, per insertion 2.023
n = 1000000: total cost 2048575, per insertion 2.049
The amortized column is 2, then 3 forever, while the actual cost spikes at insertions 2, 3, 5 and 9. The average per insertion approaches 3 from below when is just past a power of 2, and is lower in between.
Other growth factors
Why double? Expanding by a factor instead, the copies are up to about , a geometric series with sum at most about , so the amortized cost is at most about : 3 for , 4 for , 2.5 for . The measured average for a particular is lower, depending on how full the last block is. Larger factors copy less but waste more memory: right after an expansion only a fraction of the block is used. Growing by a constant number of slots is a different story entirely: with extra slots per expansion, the copies are , about in total, quadratic.
import math
def total_cost(n, grow):
num, size, total = 0, 1, 0
for _ in range(n):
if num == size:
total += num
size = grow(size)
total += 1
num += 1
return total, size
n = 100000
for name, grow in [("factor 1.5", lambda s: max(s + 1, math.ceil(1.5 * s))),
("factor 2", lambda s: 2 * s),
("factor 3", lambda s: 3 * s),
("+1000 slots", lambda s: s + 1000)]:
t, size = total_cost(n, grow)
print(f"{name:12}: {t / n:6.2f} per insertion, final block {size:6} slots, load factor {n / size:.2f}")factor 1.5 : 3.76 per insertion, final block 138254 slots, load factor 0.72
factor 2 : 2.31 per insertion, final block 131072 slots, load factor 0.76
factor 3 : 1.89 per insertion, final block 177147 slots, load factor 0.56
+1000 slots : 50.50 per insertion, final block 100001 slots, load factor 1.00
The constant-increment strategy costs about 50 elementary insertions per insertion at , and the number keeps growing with ; every multiplicative strategy stays bounded. Real libraries pick factors from about 1.125 to 2: CPython's lists over-allocate by about 12.5 percent plus a small constant, MSVC's std::vector grows by 1.5 and libstdc++'s (GCC) by 2.
In C++
std::vector exposes its block size as capacity(). The program records every capacity change and counts the elements copied, using a type whose move constructor increments a counter. (With GCC's libstdc++ the capacity doubles; other libraries would print different capacities but the same bounded average.)
#include <cstdio>
#include <vector>
long long moves = 0;
struct Tracked {
int v;
explicit Tracked(int x) : v(x) {}
Tracked(const Tracked& o) : v(o.v) { ++moves; }
Tracked(Tracked&& o) noexcept : v(o.v) { ++moves; }
};
int main() {
std::vector<Tracked> a;
size_t last_capacity = a.capacity();
std::printf("capacities:");
const int n = 1000000;
for (int i = 0; i < n; ++i) {
a.emplace_back(i);
if (a.capacity() != last_capacity) {
last_capacity = a.capacity();
if (last_capacity <= 64) std::printf(" %zu", last_capacity);
}
}
std::printf(" ... %zu\n", a.capacity());
std::printf("%d insertions, %lld elements moved by reallocation: %.3f per insertion\n",
n, moves, static_cast<double>(moves) / n);
}capacities: 1 2 4 8 16 32 64 ... 1048576
1000000 insertions, 1048575 elements moved by reallocation: 1.049 per insertion
The copies per insertion stay below 2 (plus the insertion itself, below 3, as proved). Reserving space with a.reserve(n) in advance avoids all of them when is known.
Test yourself
A doubling table currently has size 16 and 16 items. What does the next insertion cost, and what is its amortized cost with ?
- 17 and 3
- 17 and 17
- 1 and 3
- 16 and 2
Why is never negative for a table that only expands?
- Because
- Because after the first expansion the table is always at least half full
- Because is a power of 2
- It can be negative; the method still works
Growing the table by a constant 100 slots each time it is full, what is the total cost of insertions?