TExcelTAD

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 TT stores T.numT.\mathit{num} items in an allocated block of T.sizeT.\mathit{size} slots, with num≤size\mathit{num} \le \mathit{size}. Its load factor is α(T)=num/size\alpha(T) = \mathit{num} / \mathit{size} (and α=1\alpha = 1 for the empty table with size=0\mathit{size} = 0). Inserting into a table with a free slot costs 1. Inserting into a full table first allocates a block twice as large, copies the num\mathit{num} old items into it (cost 1 each), frees the old block, and then inserts (cost 1).

text
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 + 1

The cost of insertion ii is ci=ic_i = i if i−1i - 1 is a power of 2 (the table was full with i−1i - 1 items and they are all copied), and ci=1c_i = 1 otherwise. The worst single insertion is Θ(n)\Theta(n).

Aggregate analysis

The expansions happen at insertions 2,3,5,9,17,…2, 3, 5, 9, 17, \ldots, copying 1,2,4,8,…1, 2, 4, 8, \ldots items. So the total cost of nn insertions is

∑i=1nci ≤ n+∑j=0⌊lg⁡(n−1)⌋2j < n+2n=3n.\sum_{i=1}^{n} c_i \ \le\ n + \sum_{j=0}^{\lfloor \lg (n-1) \rfloor} 2^j \ <\ n + 2n = 3n.

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 mm, the table holds m/2m/2 items and no credit. The next m/2m/2 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 mm 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 num\mathit{num} when the table is full. That is

Φ(T)=2⋅T.num−T.size.\Phi(T) = 2 \cdot T.\mathit{num} - T.\mathit{size}.

It is 0 right after an expansion (num=size/2\mathit{num} = \mathit{size}/2), equal to num\mathit{num} when full, and never negative since the table is always at least half full (from the first expansion on; the empty table has Φ=0\Phi = 0).

  • No expansion: ci=1c_i = 1, num\mathit{num} rises by 1, size\mathit{size} unchanged: c^i=1+2=3\hat{c}_i = 1 + 2 = 3.
  • Expansion from size mm (full, num=m\mathit{num} = m) to 2m2m: ci=m+1c_i = m + 1, and Φ\Phi goes from 2m−m=m2m - m = m to 2(m+1)−2m=22(m + 1) - 2m = 2, so c^i=(m+1)+2−m=3\hat{c}_i = (m + 1) + 2 - m = 3.

Every insertion has amortized cost exactly 3 (the very first one, which allocates the first slot, has c^=1+1=2\hat{c} = 1 + 1 = 2).

python · try it yourself
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 nn is just past a power of 2, and is lower in between.

Other growth factors

Why double? Expanding by a factor γ>1\gamma > 1 instead, the copies are 1,γ,γ2,…1, \gamma, \gamma^2, \ldots up to about nn, a geometric series with sum at most about γγ−1n\frac{\gamma}{\gamma - 1} n, so the amortized cost is at most about 1+γγ−11 + \frac{\gamma}{\gamma - 1}: 3 for γ=2\gamma = 2, 4 for γ=1.5\gamma = 1.5, 2.5 for γ=3\gamma = 3. The measured average for a particular nn is lower, depending on how full the last block is. Larger factors copy less but waste more memory: right after an expansion only a 1γ\frac{1}{\gamma} fraction of the block is used. Growing by a constant number of slots is a different story entirely: with kk extra slots per expansion, the copies are k,2k,3k,…k, 2k, 3k, \ldots, about n22k\frac{n^2}{2k} in total, quadratic.

python · try it yourself
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 n=100,000n = 100{,}000, and the number keeps growing with nn; 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.)

cpp · try it yourself
#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 nn 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 Φ=2 num−size\Phi = 2\,\mathit{num} - \mathit{size}?

  1. 17 and 3
  2. 17 and 17
  3. 1 and 3
  4. 16 and 2

Why is Φ=2 num−size\Phi = 2\,\mathit{num} - \mathit{size} never negative for a table that only expands?

  1. Because num≥size\mathit{num} \ge \mathit{size}
  2. Because after the first expansion the table is always at least half full
  3. Because size\mathit{size} is a power of 2
  4. 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 nn insertions?

  1. Θ(n)\Theta(n)
  2. Θ(nlg⁡n)\Theta(n \lg n)
  3. Θ(n2)\Theta(n^2)
  4. Θ(n2/lg⁡n)\Theta(n^2 / \lg n)