Sub topic 14
Cache-Friendly Hash Tables: Open Addressing Versus Chaining
This chapter assumes you can read C, know how a hash table works at the level of "hash the key, pick a bucket, resolve collisions", and have read the earlier chapters on cache lines, spatial locality, and arrays versus linked structures. Here you will compare the two main collision strategies by counting the cache lines each lookup touches.
Why big-O hides the real cost
A hash table lookup is O(1) on average under both strategies. The constant factor is dominated by cache misses, because each miss to main memory costs roughly as much as hundreds of arithmetic instructions. Two tables with the same big-O can differ several times in speed depending on how many distinct cache lines a lookup reads.
The hash function scatters keys, so the first access to a table much larger than the cache is almost always a miss. You cannot avoid that one. What you can control is how many additional misses follow it.
Chaining: one miss per hop
In a chained table, each bucket holds a pointer to a linked list of nodes. A lookup does this:
- Load the bucket pointer from the bucket array (one cache miss).
- Load the first node to compare its key (another miss, since nodes are allocated separately).
- Follow
nextto the following node (another miss), and so on.
Each hop depends on the previous load, so the CPU cannot overlap the misses, and the prefetcher cannot guess where the next node lives. A lookup that passes through k nodes costs about k + 1 misses.
struct ChainNode {
unsigned long long key;
unsigned long long value;
struct ChainNode *next; /* 8 bytes of pointer overhead per entry */
};
struct ChainTable {
struct ChainNode **buckets;
unsigned long long capacity;
};Chaining also pays for allocator overhead and pointer storage on every entry. At 24 bytes per node here, a 64-byte line holds fewer than three entries, and nodes from the allocator may be scattered across memory.
Open addressing: probe neighbouring slots
In an open-addressing table, every entry lives directly in one flat array. On a collision, the table tries another slot. With linear probing, the next slot is simply the adjacent one. Adjacent slots share cache lines, so the collision resolution that costs a chained table another miss costs a linear-probing table almost nothing.
The program below is a complete fixed-capacity table with linear probing. It reserves key 0 as the "empty" marker, which lets calloc initialize the table to empty.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
uint64_t key; /* 0 means empty */
uint64_t value;
} Slot; /* 16 bytes: four slots per 64-byte line */
typedef struct {
Slot *slots;
unsigned bits; /* capacity = 2^bits, bits >= 1 */
size_t count;
} Table;
static size_t capacity(const Table *t) { return (size_t)1 << t->bits; }
/* Fibonacci hashing: multiply, then keep the top bits. */
static size_t home(const Table *t, uint64_t key) {
return (size_t)((key * 0x9E3779B97F4A7C15ull) >> (64 - t->bits));
}
int table_init(Table *t, unsigned bits) {
t->slots = calloc((size_t)1 << bits, sizeof(Slot));
t->bits = bits;
t->count = 0;
return t->slots != NULL;
}
/* Returns 1 on success, 0 if key is 0 or the load factor would exceed 0.7. */
int table_put(Table *t, uint64_t key, uint64_t value) {
if (key == 0) return 0;
if ((t->count + 1) * 10 > capacity(t) * 7) return 0;
size_t mask = capacity(t) - 1;
for (size_t i = home(t, key);; i = (i + 1) & mask) {
if (t->slots[i].key == key) { t->slots[i].value = value; return 1; }
if (t->slots[i].key == 0) {
t->slots[i].key = key;
t->slots[i].value = value;
t->count++;
return 1;
}
}
}
int table_get(const Table *t, uint64_t key, uint64_t *out) {
if (key == 0) return 0;
size_t mask = capacity(t) - 1;
for (size_t i = home(t, key); t->slots[i].key != 0; i = (i + 1) & mask) {
if (t->slots[i].key == key) { *out = t->slots[i].value; return 1; }
}
return 0; /* reached an empty slot: key is absent */
}
int main(void) {
Table t;
if (!table_init(&t, 4)) return 1;
for (uint64_t k = 1; k <= 10; k++) table_put(&t, k, k * k);
uint64_t v;
if (table_get(&t, 7, &v)) printf("7 -> %llu\n", (unsigned long long)v);
printf("11 present: %d\n", table_get(&t, 11, &v));
free(t.slots);
return 0;
}The probe loop terminates because the load factor cap guarantees at least one empty slot. The power-of-two capacity turns the wrap-around into a bitwise AND instead of a division.
Comparing the two designs
| Property | Chaining | Open addressing (linear probing) |
|---|---|---|
| Misses per lookup | One per node visited, plus the bucket | Often one or two lines in total |
| Per-entry overhead | Pointer and allocator header | None beyond the slot |
| Tolerates load factor above 1 | Yes | No, must stay below 1 |
| Deletion | Unlink the node | Needs tombstones or backward shifting |
| Pointers to entries stay valid on growth | Yes | No, the array is reallocated |
| Hardware prefetch helps | No | Yes, for sequential probing |
The cost of open addressing: load factor and clustering
Linear probing creates primary clusters, which are runs of occupied slots. A key that hashes into a cluster must walk to its end, and it extends the cluster by one. The expected number of probes grows sharply with the load factor α (the fraction of slots occupied):
| α | Probes, key present | Probes, key absent |
|---|---|---|
| 0.5 | 1.5 | 2.5 |
| 0.7 | 2.2 | 6.1 |
| 0.9 | 5.5 | 50.5 |
These are the standard expectations for linear probing with a good hash. They show why implementations cap the load factor, commonly between 0.5 and 0.875, and resize before the cap. Even six probes in a 16-byte-slot table touch only two or three cache lines, so the extra probes cost far less than the same number of chain hops.
Practical details and edge cases
- Deletion. Emptying a slot would break probe sequences that pass through it. Mark it as a tombstone instead, and rebuild the table when tombstones accumulate. Another option is backward-shift deletion, which moves later entries of the cluster into the gap.
- Large values. If values are big, a slot may span several lines and the cache advantage shrinks. Store keys (and perhaps small hashes) in one dense array and keep values in a parallel array or behind an index. A miss-heavy lookup then scans only the compact key array.
- Hash quality. Linear probing is less forgiving of bad hashes than chaining. Weak low bits, as with a plain
key % capacityover sequential or aligned keys, produce long clusters. Multiplicative mixing that keeps the high bits avoids this. - Probe length variance. Robin Hood hashing reduces the worst-case probe length by letting a displaced entry steal the slot of an entry closer to its home. Production designs such as SwissTable-style tables store one metadata byte per slot and compare 16 of them with a single SIMD instruction before reading any key.
- Chaining still wins sometimes. Choose it when entries must keep stable addresses, when values are expensive to move, or when the load factor is unpredictable and resizing pauses are unacceptable.
Exercise
A slot is 16 bytes, the table array starts on a 64-byte boundary, and a failed lookup under linear probing examines 6 consecutive slots. What is the smallest and largest number of cache lines those probes can touch? Compare this with a chained lookup that visits 6 separately allocated nodes.
Show answer
Four slots fit in one 64-byte line. Six consecutive slots touch 2 lines at minimum, when the run starts at the first slot of a line (slots 0-3 and 4-5). They touch 3 lines at maximum, when the run starts at the last slot of a line (slot 3, then 4-7, then 8). The chained lookup visits 6 separate nodes, which can mean up to 6 distinct lines, plus the bucket array load. Each of those loads also depends on the previous one, so the misses cannot overlap.