Sub topic 16
How Standard Libraries Implement Hash Tables
This chapter assumes you know separate chaining, linear probing, load factor, resizing, and the difference between average and worst-case cost from the earlier chapters. It shows how real libraries combine those ideas. Their designs differ because they optimize for different things: memory use, iteration speed, pointer stability, or resistance to hostile input.
What the textbook model leaves out
The tables you built earlier are correct but simple. Production tables add several things:
- A cheaper index computation than
%, usually a bit mask on a power-of-two capacity. - A better layout for CPU caches.
- Defenses against bad hash functions and hostile keys.
- Guarantees that user code relies on, such as iteration order or stable references.
Each library chooses a point in this trade-off space. The sections below cover the main ones.
CPython: dict and set
A Python dict uses open addressing, but not the plain linear probing from earlier. Three details matter.
Compact layout. Since Python 3.6, a dict has two arrays. A sparse indices array holds small integers. A dense entries array holds (hash, key, value) records in insertion order. A lookup probes indices to find a position, then reads that record from entries. This saves memory, because the sparse array holds 1-byte to 8-byte integers instead of full records. It also makes iteration a scan over a dense array, and it gives dicts their insertion order. The order has been a language guarantee since Python 3.7.
Perturbed probing. CPython does not step by +1. It mixes the unused high bits of the hash into each step: i = (5*i + 1 + perturb) % size, then perturb >>= 5. This breaks up the clusters that linear probing creates, and every hash bit eventually influences the probe sequence.
Load limit. The table resizes when about two thirds of the index slots are used. That is a low limit, which keeps probe sequences short.
Hashes are also not what you might expect:
print(hash(5))
print(hash(-1), hash(-2))
print(hash("a") == hash("a"))Small integers hash to themselves. -1 is reserved as an error signal in CPython's C API, so hash(-1) returns -2 and collides with hash(-2). String hashes are randomized per process (see the hash flooding chapter), so hash("a") differs between runs but stays constant within one run.
A model of the compact layout
This simplified class shows the two-array idea. It uses linear probing for clarity, and it always doubles on resize. Deletion marks the index slot as deleted and leaves a hole in entries. The hole disappears at the next resize.
_EMPTY = -1
_DELETED = -2
class CompactDict:
def __init__(self, capacity=8):
self._indices = [_EMPTY] * capacity
self._entries = [] # (hash, key, value) or None for a deleted record
self._live = 0
def _probe(self, key):
h = hash(key)
n = len(self._indices)
i = h % n
while True:
ix = self._indices[i]
if ix == _EMPTY:
return h, i, None
if ix >= 0:
e = self._entries[ix]
if e[0] == h and e[1] == key:
return h, i, ix
i = (i + 1) % n
def _append(self, h, i, key, value):
self._entries.append((h, key, value))
self._indices[i] = len(self._entries) - 1
self._live += 1
def put(self, key, value):
h, i, ix = self._probe(key)
if ix is not None:
self._entries[ix] = (h, key, value)
return
if (len(self._entries) + 1) * 3 > len(self._indices) * 2:
self._resize()
h, i, _ = self._probe(key)
self._append(h, i, key, value)
def get(self, key, default=None):
_, _, ix = self._probe(key)
return default if ix is None else self._entries[ix][2]
def remove(self, key):
_, i, ix = self._probe(key)
if ix is None:
return False
self._indices[i] = _DELETED
self._entries[ix] = None
self._live -= 1
return True
def _resize(self):
live = [e for e in self._entries if e is not None]
self._indices = [_EMPTY] * (len(self._indices) * 2)
self._entries = []
self._live = 0
for h, k, v in live:
_, i, _ = self._probe(k)
self._append(h, i, k, v)
def items(self):
return [(k, v) for e in self._entries if e is not None for _, k, v in [e]]
d = CompactDict()
for name, n in [("a", 1), ("b", 2), ("c", 3)]:
d.put(name, n)
d.remove("b")
d.put("d", 4)
print(d.items())
print(d.get("c"), d.get("b"))The output is [('a', 1), ('c', 3), ('d', 4)], then 3 None. Insertion order falls out of the layout, with no extra bookkeeping.
A Python set uses the same open-addressing approach with a different layout. It stores only keys, in a single array of hash and key pairs, and it does not preserve insertion order.
Java: HashMap
Java's HashMap uses separate chaining with several refinements:
- The capacity is always a power of two, 16 by default. The index is
(n - 1) & hash, which is a mask and avoids division. - A power-of-two mask uses only the low bits of the hash. To compensate, Java first spreads the hash with
h ^ (h >>> 16), mixing high bits into low bits. - The default load factor is 0.75. The table doubles when the entry count exceeds capacity times load factor.
- If one bucket's chain grows to 8 nodes and the table has at least 64 buckets, the chain becomes a balanced tree. This bounds the worst case at O(log n) per bucket when keys are
Comparable, or when they at least have a usable tie-breaking order. If the table is smaller than 64 buckets, it resizes instead. A bucket shrinks back to a list at 6 nodes.
This design shows why the worst-case discussion matters in practice. Treeification is a direct defense against collision-heavy input.
C++: std::unordered_map
The C++ standard does not name a layout, but its interface effectively requires chaining. It exposes buckets (bucket_count, bucket_size, begin(n)). It also guarantees that references to elements stay valid after a rehash. Open addressing moves elements on resize, so it cannot meet that guarantee.
The cost is memory: each element is usually its own heap-allocated node, which means pointer chasing and poor cache behavior. The default max_load_factor is 1.0. Because of that stability guarantee, many performance-sensitive C++ projects use third-party tables such as Abseil's flat_hash_map instead.
Rust: HashMap
Since Rust 1.36, std::collections::HashMap is built on hashbrown, an implementation of the SwissTable design from Google. It uses open addressing with a separate array of one-byte control values. Each control byte records whether a slot is empty, deleted, or full, and a full slot also stores 7 bits of the hash. A lookup compares a whole group of control bytes at once with SIMD instructions and touches the actual keys only on a likely match. The table tolerates a high load, up to 7/8.
The default hasher is SipHash 1-3 with random keys per map. It is slower than simple hashes on short keys, but it resists flooding. You can swap the hasher through a type parameter when you trust your input and need speed.
Go: map
Before Go 1.24, a map used buckets of 8 key-value pairs with overflow chains and a load factor of 6.5 per bucket. Go 1.24 moved to a SwissTable-style implementation. Go deliberately randomizes iteration order so programs cannot depend on it. Maps grow incrementally in both designs, which avoids one long pause at resize.
Comparing the designs
| Library | Collision strategy | Notable choices | Iteration order |
|---|---|---|---|
| CPython dict | Open addressing, perturbed probing | Compact index and entries arrays, load limit about 2/3 | Insertion order |
| Java HashMap | Chaining, trees for long chains | Power-of-two size, hash spreading, load 0.75 | Unspecified |
| C++ unordered_map | Chaining (effectively required) | Stable references, bucket interface | Unspecified |
| Rust HashMap | Open addressing (SwissTable) | SIMD control bytes, SipHash by default | Unspecified |
| Go map | Buckets of 8, then SwissTable | Randomized iteration, incremental growth | Randomized |
Practical consequences
- Do not rely on order unless the language guarantees it. Python dicts do. Java and Rust maps do not, and Go makes it random on purpose.
- Do not mutate while iterating. Resizing moves entries. Python raises
RuntimeErrorif a dict changes size during iteration, and Java's iterators throwConcurrentModificationException. - Reserve capacity when you know the size. Pre-sizing (
HashMap(n),reserve,with_capacity) avoids repeated resizes. - Deleting does not shrink memory in most libraries. A map that once held millions of entries keeps its large arrays until it is rebuilt.
Exercise
In CPython's compact dict, why does deleting a key leave a hole in the entries array instead of shifting later records down? What cleans up the holes?
Show answer
Shifting records would change their positions, and the sparse indices array stores those positions. Every affected index slot would need updating, which makes deletion cost O(n). Leaving a hole and marking the index slot as deleted keeps removal O(1) on average, and lookups for other keys keep working because probe sequences are not broken. The holes are removed when the table resizes, because the rebuild copies only live records into a fresh entries array.
Exercise
Why can std::unordered_map not easily use open addressing, while Rust's HashMap can?
Show answer
The C++ standard exposes a bucket interface and guarantees that references and pointers to elements stay valid across a rehash. Open addressing stores entries inside the slot array and moves them when the table grows, which would invalidate those references. Rust's borrow rules already forbid holding references into a map while inserting, so its map can move entries freely.