Sub topic 11
Shrinking the Table and Avoiding Thrashing
This chapter assumes you know how a chained hash table resizes. You should know that growth is triggered when the load factor passes a threshold, and that rehashing moves every entry into a new bucket array. You should also be able to read simple Python.
Why shrink at all
A table that only grows keeps its peak capacity forever. Suppose you insert a million entries and then delete all but ten. The bucket array still has about 1.3 million slots. The load factor is nearly zero, so lookups stay fast, but the memory is wasted. Iteration is also slower, because it must walk every empty bucket.
Shrinking fixes this. When the load factor falls low enough, the table allocates a smaller array and rehashes into it. The mechanism is the same as growth, with a smaller target capacity.
The naive policy and thrashing
The obvious design mirrors growth: double when the load factor exceeds 0.75, and halve when it drops below 0.75 divided by 2, or 0.375. This looks symmetric, but it has a flaw.
Say capacity is 8 and the table holds 6 entries, a load factor of exactly 0.75. One more insert makes it 7 of 8, so the table doubles to 16, giving a load factor of 0.4375. Now delete one entry. If the shrink threshold were 0.5, that would give 6 of 16, or 0.375, and the table would halve again. The next insert would trigger another doubling.
An alternating insert and delete at the boundary now costs a full rehash on every operation. This is called thrashing. Each operation is O(n), and the amortized argument from the previous chapter no longer holds.
Hysteresis: leaving a gap
The fix is hysteresis, which means using different thresholds for the two directions so there is a wide dead zone between them. A common choice is to shrink only when the load factor falls to one quarter of the capacity, and to shrink by half.
Work through it with a grow threshold of 0.75:
- After doubling, the load factor is about 0.375.
- After shrinking at 0.25 and halving, the load factor is about 0.5.
- Both results sit far from either trigger.
After any resize, the table must absorb a large number of operations before the next one. Growth at 0.375 needs the table to roughly double in size again before it exceeds 0.75. Shrinking from 0.5 needs the size to drop by half before it reaches 0.25. Each resize costs O(n), but at least on the order of n operations must pass between resizes, so the cost per operation stays O(1) amortized.
Implementation
This subclass adds shrinking to the chained table from earlier. It overrides remove, which the base class did not define, so the example includes a minimal version.
class ShrinkingHashTable:
def __init__(self, capacity=8, max_load=0.75, min_load=0.25, min_capacity=8):
self._buckets = [[] for _ in range(capacity)]
self._size = 0
self._max_load = max_load
self._min_load = min_load
self._min_capacity = min_capacity
def load_factor(self):
return self._size / len(self._buckets)
def _index(self, key):
return hash(key) % len(self._buckets)
def put(self, key, value):
bucket = self._buckets[self._index(key)]
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
return
bucket.append((key, value))
self._size += 1
if self.load_factor() > self._max_load:
self._resize(len(self._buckets) * 2)
def get(self, key, default=None):
for k, v in self._buckets[self._index(key)]:
if k == key:
return v
return default
def remove(self, key):
bucket = self._buckets[self._index(key)]
for i, (k, _) in enumerate(bucket):
if k == key:
del bucket[i]
self._size -= 1
new_capacity = len(self._buckets) // 2
if (self.load_factor() < self._min_load
and new_capacity >= self._min_capacity):
self._resize(new_capacity)
return True
return False
def _resize(self, new_capacity):
old_buckets = self._buckets
self._buckets = [[] for _ in range(new_capacity)]
for bucket in old_buckets:
for key, value in bucket:
self._buckets[self._index(key)].append((key, value))
table = ShrinkingHashTable()
for n in range(100):
table.put(n, n)
print(len(table._buckets))
for n in range(95):
table.remove(n)
print(len(table._buckets), table._size)The min_capacity floor stops the table from shrinking to a handful of buckets. Without it, a table that is repeatedly emptied and refilled would resize at every small size.
Common mistakes
- Choosing a shrink threshold at or above half the grow threshold, which allows thrashing.
- Forgetting a minimum capacity, so small tables resize constantly.
- Shrinking inside a loop that is deleting entries during iteration, which invalidates the iteration.
- Assuming shrinking is always desirable. Many libraries never shrink automatically, because a table that was large once often becomes large again.
Exercise
A table grows at load factor 0.75 and doubles its capacity. A developer sets the shrink threshold to 0.4 and halves the capacity. Starting at capacity 16 with 12 entries, give a sequence of one insert followed by one delete that causes a resize on every operation.
Show answer
Insert one entry: 13 of 16 is 0.8125, which exceeds 0.75, so the table doubles to 32 and the load factor becomes 13/32, about 0.41. Delete one entry: 12 of 32 is 0.375, which is below 0.4, so the table halves to 16 and the load factor returns to 0.75. Repeating this insert and delete pair resizes on every operation. A shrink threshold of 0.25 would leave 12 of 32 in place.