Dynamic Arrays and Doubling
An array gives constant-time access to position because its elements sit in one contiguous block of memory: the address of is the start address plus 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 appends cost ; growing by a constant factor makes them cost , so a single append costs 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 to .
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 + 1Reading or writing position is one access, as with a plain array. Only APPEND can be expensive: when the block is full, it copies all size elements.
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 appends
Count the element copies made by resizes during appends, starting from capacity 1. Resizes happen when the size reaches where is the largest power of two below , and each copies that many elements:
Adding the ordinary writes, appends do fewer than element writes in total. The average cost per append is below 3, a constant, even though a single append can cost . 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 instead (capacity ) the resize at size copies elements, and the total is about : quadratic. The program compares growth rules.
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 falls between resizes), while additive growth gets worse in proportion to . 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.
#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 , append one element (resize to , copying elements), then remove two (the array is at the half mark: shrink, copying again), then append two, and so on. Every few operations copy 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.
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 amortized cost, with the potential method.
In practice: Python's
listover-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 , with more frequent but smaller copies.std::vectornever shrinks on its own; callshrink_to_fit()to ask for it.
Test yourself
Starting from capacity 1 and doubling, how many element copies do resizes make during 1000 appends?
- 999
- 1023
- 2047
- about 500,000
A dynamic array grows by a constant 100 slots each time. What is the total cost of appends?
Why does a dynamic array shrink at a quarter full rather than at half full?
- To save more memory
- So that alternating appends and pops near a resize point cannot trigger a resize every time
- Because halving is impossible at half full
- Because pops are cheaper than appends