TExcelTAD

Dynamic Arrays and Doubling

An array gives constant-time access to position ii because its elements sit in one contiguous block of memory: the address of a[i]a[i] is the start address plus ii times the element size. The price is a fixed size. A dynamic array hides that limitation: it keeps a block with some spare room, and when the room runs out it allocates a bigger block and copies everything over. Python's list, C++'s std::vector and Java's ArrayList all work this way.

The interesting question is how much bigger the new block should be. Growing by a constant amount makes nn appends cost Θ(n2)\Theta(n^2); growing by a constant factor makes them cost Θ(n)\Theta(n), so a single append costs O(1)O(1) on average over any sequence. This is the first example in the track of amortized analysis, which the course Design Techniques treats in general.

The structure

A dynamic array stores three things: a block of capacity slots, the number size of slots in use, and the elements in positions 00 to size−1\textit{size} - 1.

text
APPEND(d, x)
1  if d.size == d.capacity
2      new = allocate an array of 2 * d.capacity slots      // capacity 0 grows to 1
3      for i = 0 to d.size - 1
4          new[i] = d.block[i]                           // one copy per element
5      d.block = new, d.capacity = 2 * d.capacity
6  d.block[d.size] = x
7  d.size = d.size + 1

Reading or writing position ii is one access, as with a plain array. Only APPEND can be expensive: when the block is full, it copies all size elements.

python · try it yourself
class DynArray:
    def __init__(self, factor=2):
        self.block, self.size, self.factor = [None], 0, factor
        self.copies = 0                        # element copies made by resizes
    def append(self, x):
        if self.size == len(self.block):
            new = [None] * max(self.size + 1, int(len(self.block) * self.factor))
            for i in range(self.size):
                new[i] = self.block[i]
                self.copies += 1
            self.block = new
        self.block[self.size] = x
        self.size += 1
    def __getitem__(self, i):
        if not 0 <= i < self.size:
            raise IndexError(i)
        return self.block[i]

d = DynArray()
for x in range(17):
    before = len(d.block)
    d.append(x * x)
    if len(d.block) != before:
        print(f"append #{x + 1:2}: capacity {before:2} -> {len(d.block):2}, copies so far {d.copies}")
print("size", d.size, "capacity", len(d.block), "d[16] =", d[16])
append # 2: capacity  1 ->  2, copies so far 1
append # 3: capacity  2 ->  4, copies so far 3
append # 5: capacity  4 ->  8, copies so far 7
append # 9: capacity  8 -> 16, copies so far 15
append #17: capacity 16 -> 32, copies so far 31
size 17 capacity 32 d[16] = 256

The cost of nn appends

Count the element copies made by resizes during nn appends, starting from capacity 1. Resizes happen when the size reaches 1,2,4,…,2k1, 2, 4, \ldots, 2^k where 2k2^k is the largest power of two below nn, and each copies that many elements:

copies=1+2+4+⋯+2k=2k+1−1<2n\text{copies} = 1 + 2 + 4 + \cdots + 2^k = 2^{k+1} - 1 < 2n

Adding the nn ordinary writes, nn appends do fewer than 3n3n element writes in total. The average cost per append is below 3, a constant, even though a single append can cost nn. That average holds for every sequence of appends, not just on average over random inputs, which is what makes it an amortized bound rather than an expected one.

With a constant increment cc instead (capacity c,2c,3c,…c, 2c, 3c, \ldots) the resize at size jcjc copies jcjc elements, and the total is about c(1+2+⋯+n/c)≈n2/(2c)c(1 + 2 + \cdots + n/c) \approx n^2/(2c): quadratic. The program compares growth rules.

python · try it yourself
class Counter:
    def __init__(self, grow):
        self.cap, self.size, self.copies, self.grow = 1, 0, 0, grow
    def append(self):
        if self.size == self.cap:
            self.copies += self.size
            self.cap = self.grow(self.cap)
        self.size += 1

rules = {
    "double":    lambda c: 2 * c,
    "times 1.5": lambda c: max(c + 1, c * 3 // 2),
    "plus 10":   lambda c: c + 10,
    "plus 100":  lambda c: c + 100,
}
print(f"{'n':>7}" + "".join(f"{name:>12}" for name in rules))
for n in [1_000, 10_000, 100_000]:
    row = []
    for grow in rules.values():
        d = Counter(grow)
        for _ in range(n):
            d.append()
        row.append(d.copies / n)
    print(f"{n:>7}" + "".join(f"{r:>12.2f}" for r in row))
      n      double   times 1.5     plus 10    plus 100
   1000        1.02        2.14       49.60        4.51
  10000        1.64        2.43      499.60       49.51
 100000        1.31        2.77     4999.60      499.51

The table shows copies per append. Both multiplicative rules stay bounded (between 1 and 2 for doubling, between 2 and 3 for factor 1.5, depending on where nn falls between resizes), while additive growth gets worse in proportion to nn. A factor of 1.5 copies more but wastes less memory: right after a resize at most a third of the block is empty instead of half. Microsoft's C++ standard library uses 1.5 for std::vector, for that reason.

In C++

std::vector in GCC's standard library doubles its capacity. The program records each capacity change of a vector during 100 push_back calls, then repeats the experiment with a hand-written dynamic array that counts its copies.

cpp · try it yourself
#include <cstdio>
#include <memory>
#include <vector>

template <typename T>
class DynArray {
    std::unique_ptr<T[]> block_ = std::make_unique<T[]>(1);
    std::size_t size_ = 0, cap_ = 1;
public:
    long copies = 0;
    void push_back(const T& x) {
        if (size_ == cap_) {
            auto bigger = std::make_unique<T[]>(2 * cap_);
            for (std::size_t i = 0; i < size_; ++i) { bigger[i] = block_[i]; ++copies; }
            block_ = std::move(bigger);
            cap_ *= 2;
        }
        block_[size_++] = x;
    }
    T& operator[](std::size_t i) { return block_[i]; }
    std::size_t size() const { return size_; }
};

int main() {
    std::vector<int> v;
    std::size_t last = v.capacity();
    std::printf("std::vector capacities:");
    for (int i = 0; i < 100; ++i) {
        v.push_back(i);
        if (v.capacity() != last) { last = v.capacity(); std::printf(" %zu", last); }
    }
    std::printf("\n");

    DynArray<int> d;
    for (int i = 0; i < 1000000; ++i) d.push_back(i);
    std::printf("DynArray: %zu elements, %ld copies (%.2f per push), d[999999] = %d\n",
                d.size(), d.copies, double(d.copies) / d.size(), d[999999]);
}
std::vector capacities: 1 2 4 8 16 32 64 128
DynArray: 1000000 elements, 1048575 copies (1.05 per push), d[999999] = 999999

Shrinking without thrashing

If elements can also be removed from the end, a dynamic array may want to give memory back. The obvious rule, "halve the capacity when the array is half full", is a trap. Take a full array of capacity 2k2^k, append one element (resize to 2k+12^{k+1}, copying 2k2^k elements), then remove two (the array is at the half mark: shrink, copying again), then append two, and so on. Every few operations copy Θ(n)\Theta(n) elements.

The fix is to shrink only when the array is a quarter full, and then to half the capacity. After any resize the array is exactly half full, so at least a quarter of the capacity's worth of operations must happen before the next one, and their cost pays for it. The program alternates appends and pops around a power of two under both rules.

python · try it yourself
class Shrinking:
    def __init__(self, shrink_at):
        self.cap, self.size, self.copies, self.shrink_at = 1, 0, 0, shrink_at
    def append(self):
        if self.size == self.cap:
            self.copies += self.size; self.cap *= 2
        self.size += 1
    def pop(self):
        self.size -= 1
        if self.cap > 1 and self.size <= self.cap * self.shrink_at:
            self.copies += self.size; self.cap //= 2

for shrink_at, name in [(1 / 2, "shrink at 1/2 full"), (1 / 4, "shrink at 1/4 full")]:
    d = Shrinking(shrink_at)
    for _ in range(1024):
        d.append()
    start = d.copies
    for _ in range(1000):                  # append twice, pop twice, around size 1024
        d.append(); d.append(); d.pop(); d.pop()
    print(f"{name}: {d.copies - start:>9,} copies for 4000 operations, final capacity {d.cap}")
shrink at 1/2 full: 2,048,000 copies for 4000 operations, final capacity 1024
shrink at 1/4 full:     1,024 copies for 4000 operations, final capacity 2048

With the half rule every round of four operations triggers a grow and a shrink, 2048 copies per round. With the quarter rule there is one resize at the start and none after. The amortized analysis lessons prove that this rule keeps every sequence of appends and pops at O(1)O(1) amortized cost, with the potential method.

In practice: Python's list over-allocates by about one eighth plus a small constant, so its growth factor approaches 1.125 for large lists. That is still multiplicative, so appends stay amortized O(1)O(1), with more frequent but smaller copies. std::vector never shrinks on its own; call shrink_to_fit() to ask for it.

Test yourself

Starting from capacity 1 and doubling, how many element copies do resizes make during 1000 appends?

  1. 999
  2. 1023
  3. 2047
  4. about 500,000

A dynamic array grows by a constant 100 slots each time. What is the total cost of nn appends?

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

Why does a dynamic array shrink at a quarter full rather than at half full?

  1. To save more memory
  2. So that alternating appends and pops near a resize point cannot trigger a resize every time
  3. Because halving is impossible at half full
  4. Because pops are cheaper than appends