Sub topic 7
Shrinking without thrashing
This chapter assumes you know the doubling dynamic array and its aggregate bound from the earlier chapters. You should also be comfortable with the accounting and potential methods. Growing an array is the easy half of resizing. Shrinking it looks like the mirror image, but the obvious mirror image breaks the amortised bound.
Why shrink at all
A dynamic array that only grows keeps its peak memory forever. Suppose a program stores a million items and then removes all but ten. The array still holds a million slots. For a long-running process, or one with many such arrays, that waste matters. We want the capacity to stay proportional to the current size, so that memory use is always O(n) for n stored elements.
Shrinking means allocating a smaller array and copying every element into it. That costs O(n), the same as growing. The question is when to trigger it.
The naive rule and why it thrashes
The symmetric-looking rule is: double when the array is full, and halve when it is half full. Trace it from an array of capacity c that is exactly full, with size n = c.
appendfinds the array full. It allocates capacity 2c and copies c elements. The size is now c + 1.popbrings the size back to c. That is half of the capacity 2c, so the rule halves the array. It allocates capacity c and copies c elements. The array is full again.- The next
appendis back at step 1.
Every operation now copies c elements. A sequence of m alternating append and pop calls costs Θ(m · c), so the amortised cost per operation is Θ(n), not O(1). This behaviour is called thrashing: the structure flips between two states, and each flip costs a full copy.
The root cause is that a resize leaves the array in a state that sits right next to the trigger for the opposite resize. The grow step leaves the array just over half full, and the shrink threshold is exactly half full. Nothing separates the two thresholds, so no amount of cheap work can accumulate between expensive operations.
The fix: leave a gap between the thresholds
Use two different thresholds:
- Grow when the array is full: double the capacity.
- Shrink when the size falls to one quarter of the capacity: halve the capacity.
Look at the state right after each resize.
- After a grow from capacity c, the new capacity is 2c and the size is c + 1. The array is just over half full. The next grow needs the size to reach 2c, so at least c − 1 more appends. The next shrink needs the size to fall to c/2, so at least c/2 + 1 pops.
- After a shrink from capacity c, the new capacity is c/2 and the size is c/4. The array is exactly half full. The next shrink needs the size to fall to c/8, so c/8 more pops. The next grow needs the size to reach c/2, so c/4 more appends.
In every case, at least a constant fraction of the capacity worth of cheap operations must happen before the next resize. A resize copies a number of elements proportional to the capacity, so the copy cost is paid for by the cheap operations between resizes. This is the same argument as the aggregate method, now run in both directions.
The shrink factor and the shrink threshold are different quantities. We halve the capacity, which is the factor. We trigger it at one quarter, which is the threshold. The threshold must be strictly below the point where the array lands after shrinking. Any threshold below 1/2 works if the shrunk array's load stays below the grow trigger. Using 1/4 with a factor of 2 is the standard, simple choice.
Measuring it
The class below takes the shrink threshold as a parameter. shrink_at=0.5 is the naive rule and shrink_at=0.25 is the fixed rule. It never shrinks below a minimum capacity of 4.
import random
class ResizingArray:
MIN_CAPACITY = 4
def __init__(self, shrink_at):
self._shrink_at = shrink_at
self._capacity = self.MIN_CAPACITY
self._size = 0
self._data = [None] * self._capacity
self.copies = 0 # element copies caused by resizing
def __len__(self):
return self._size
def _resize(self, new_capacity):
new_data = [None] * new_capacity
for i in range(self._size):
new_data[i] = self._data[i]
self.copies += self._size
self._data = new_data
self._capacity = new_capacity
def append(self, value):
if self._size == self._capacity:
self._resize(2 * self._capacity)
self._data[self._size] = value
self._size += 1
def pop(self):
if self._size == 0:
raise IndexError("pop from empty array")
self._size -= 1
value = self._data[self._size]
self._data[self._size] = None
if (self._capacity > self.MIN_CAPACITY
and self._size <= self._capacity * self._shrink_at):
self._resize(max(self.MIN_CAPACITY, self._capacity // 2))
return value
def thrash_test(shrink_at):
arr = ResizingArray(shrink_at)
for i in range(1024): # fill to exactly the capacity
arr.append(i)
before = arr.copies
for _ in range(1000): # alternate around the boundary
arr.append(0)
arr.pop()
return arr.copies - before
print("naive (0.5): ", thrash_test(0.5))
print("quarter (0.25):", thrash_test(0.25))
# Random workload: total cost stays within 3 per operation, plus a constant.
random.seed(1)
arr = ResizingArray(0.25)
ops = 0
for _ in range(100000):
if len(arr) == 0 or random.random() < 0.5:
arr.append(ops)
else:
arr.pop()
ops += 1
assert ops + arr.copies <= 3 * ops + 2
print("random workload:", ops, arr.copies, (ops + arr.copies) / ops)The naive rule copies about two million elements over the 1000 append/pop pairs, since each operation copies 1024. The quarter rule copies about a thousand in total, from the first grow, and then no more. The random workload check confirms the bound the next section proves.
Proof with the potential method
The aggregate method is awkward here because grows and shrinks interleave in any order. The potential method handles arbitrary sequences directly. Let n be the size and c the capacity. Define:
- Φ = 2n − c when n ≥ c/2
- Φ = c/2 − n when n < c/2
Φ is never negative, and it is 0 or small right after any resize. The amortised cost of an operation is its actual cost plus the change in Φ. We count actual cost as 1 for the write plus one per element copied.
| Operation | Actual cost | Change in Φ | Amortised cost |
|---|---|---|---|
| Append, no resize, n ≥ c/2 | 1 | +2 | 3 |
| Append, no resize, n < c/2 | 1 | −1 | 0 |
| Append that grows (n = c) | c + 1 | 2 − c | 3 |
| Pop, no resize, n > c/2 | 1 | −2 | −1 |
| Pop, no resize, n ≤ c/2 | 1 | +1 | 2 |
| Pop that shrinks (n falls to c/4) | c/4 + 1 | −(c/4 − 1) | 2 |
The grow row works like this. Before the append, n = c, so Φ = 2c − c = c. After copying, the capacity is 2c and the size is c + 1, so Φ = 2(c + 1) − 2c = 2. The change is 2 − c, which cancels the cost c of the copy.
The shrink row works like this. Before the pop, the size is c/4 + 1, so Φ = c/2 − c/4 − 1 = c/4 − 1. After shrinking, the capacity is c/2 and the size is c/4, which is half full, so Φ = 0. The potential released, c/4 − 1, pays for the c/4 copies.
Every amortised cost is at most 3. Summing over m operations, the total actual cost is at most 3m + Φstart − Φend ≤ 3m + Φstart. The array starts empty with capacity 4, so Φstart = 2. This is the 3m + 2 bound that the assertion in the code checks.
Choosing the numbers
The 2 and the 1/4 are not sacred. The general constraint is that the shrink threshold must sit strictly below the load the array has after shrinking, and that load must sit strictly below the grow trigger. The wider the gaps, the fewer resizes but the more spare memory.
| Choice | Effect |
|---|---|
| Shrink threshold close to the post-shrink load | Resizes can come back to back, so the constant in the amortised bound grows. |
| Shrink threshold much lower, such as 1/8 | Fewer shrinks, but the array can hold up to 8 times more capacity than elements. |
| Never shrink | Simplest, with O(1) amortised appends. Memory stays at its peak. |
Real libraries differ. CPython's list over-allocates by about 12.5% rather than doubling, and shrinks only when the size drops below half the allocated capacity. Java's ArrayList never shrinks unless you call trimToSize(). Many language runtimes choose not to shrink automatically, because removal-heavy workloads often refill the array soon afterwards.
Edge cases
- Small arrays. Without a minimum capacity, an array of capacity 1 or 2 resizes constantly as it moves between 0 and 1 elements. Because 1/4 of 2 is not a whole number, integer division can also give a threshold of 0 and break the rule. A floor such as 4 or 8 avoids both problems.
- Clearing. After many pops, a single
clearshould release memory in one step rather than shrinking through log n intermediate arrays. - Latency. Both grow and shrink have an O(n) worst case for a single call. The amortised guarantee says nothing about the latency of that one call. A later chapter returns to this.
Exercise
Suppose a dynamic array doubles when full and halves its capacity when the size drops to one third of the capacity. Starting just after a shrink from capacity c, the size is c/6 in a new array of capacity c/2. What is the minimum number of pops that must occur before the next shrink, and why does this rule still avoid thrashing?
Show answer
The next shrink happens when the size falls to one third of c/2, which is c/6. But the size is already c/6 after the shrink, so the very next pop would trigger another shrink. This rule thrashes in a different way: a chain of shrinks, each copying about c/6 elements, on successive pops. It does not avoid thrashing. The threshold (1/3) is above the post-shrink load (1/3 of the old capacity is 1/6 of... half the new capacity, 1/3 of c/2 = c/6 equals the size), so the post-shrink state sits exactly on the trigger. A correct rule needs the threshold strictly below the post-shrink load, as with 1/4 and a halving factor, which lands at load 1/2.
Exercise
With the 1/4 shrink rule, an array of capacity 64 has just grown, so its size is 33. What is the smallest number of operations that can cause the next resize, and in which direction does it go?
Show answer
A grow needs the size to reach 64, which takes 31 more appends. A shrink needs the size to fall to 16, which takes 17 pops. The smallest is 17 pops, and the next resize is a shrink to capacity 32. That resize costs 16 copies, and the 17 preceding operations pay for it.