Building a Cache-Friendly Lookup Table for a Hot Loop
Data Structure DesignModel answerLast updated
Design a hash table for a performance-critical inner loop, covering collision strategy, memory layout, probing, load factor, prefetching, and how to benchmark it.
You are writing a compute kernel that performs millions of key lookups per second against a fixed set of integer keys. The lookup sits inside the hottest loop of the program, so every cache miss and every mispredicted branch matters.
Design the hash table that serves these lookups. In your answer, cover:
- Collision strategy. Open addressing or chaining? Justify the choice in terms of memory access patterns, not just asymptotic cost.
- Memory layout. How are keys, values and any metadata arranged in memory? How does the layout enable vectorized comparisons and contiguous reads, and what alignment do you use?
- Hashing and bit tricks. Which hash function do you use, and how do you derive the slot or group index and any small fingerprint from it without a modulo?
- Probe sequence and load factor. Which sequence do you follow after a collision, what maximum load do you allow, and why?
- Latency hiding. How would you use batching and software prefetching when the kernel looks up many keys in a row?
- Trade-offs and validation. What does your design give up (deletions, resizing, memory overhead, adversarial inputs), and how would you profile and verify it, both for correctness and for speed?
You may assume lookups vastly outnumber inserts, so a build-then-read model is acceptable. Include a short code sketch of the table structure and its lookup path.
Hints
Hint 1
Think about what a lookup really costs on hardware: dependent loads to unpredictable addresses (cache misses) and unpredictable branches usually dominate, not the operation count.
Hint 2
Consider storing a one-byte fingerprint per slot in its own contiguous array, grouped so that one vector compare checks 16 slots at once, and only touch the full keys on a fingerprint match.
Hint 3
Take the group index and the fingerprint from different bit ranges of a well-mixed 64-bit hash so they stay independent, and use a power-of-two table so masks and shifts replace modulo.
Hint 4
A single lookup is latency-bound, but a batch is not: compute all hashes first, then prefetch the lines needed for key i + D while probing key i.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
In a hot kernel, big-O is rarely the bottleneck. A lookup costs:
- Cache misses, around 100 ns each when they go to DRAM.
- Branch mispredictions, on the order of 15-20 cycles each.
- Serial dependency chains, which stop the CPU from overlapping outstanding memory requests.
A good design minimizes distinct cache lines touched, keeps branches predictable, and lets many lookups be in flight at once.
Choice: open addressing with grouped, SIMD-scanned metadata
Open addressing over chaining. Chaining follows pointers: each hop is a dependent load to an address the prefetcher cannot predict, and each node costs an allocation plus 8+ bytes of pointer overhead. Open addressing keeps everything in flat arrays, so a typical lookup touches one or two cache lines.
Layout (structure of arrays, grouped):
- Capacity is a power of two, divided into groups of 16 slots.
tags[]: 1 byte per slot. A reserved value with the high bit set (for example0x80) means empty; otherwise the byte holds 7 bits of the hash. A group's tags are 16 bytes, exactly one SSE2/NEON register.keys[]: a separate contiguous array. Sixteen 4-byte keys fill one 64-byte line. With 8-byte keys use groups of 8 so a group still maps to one line.vals[]: separate, or interleaved with keys if values are small and nearly always read on a hit.- Alignment: allocate all arrays 64-byte aligned (
alignas(64)/aligned_alloc) so no group straddles two cache lines and aligned vector loads are legal.
Separating the tags means a miss, or a hit on the first probe, touches the tag line plus at most one key line.
Hashing with bit operations
- Use a strong 64-bit mixer (murmur3 finalizer, or multiply by an odd constant such as
0x9E3779B97F4A7C15). Structured keys like sequential IDs or multiples of 4096 cluster badly with identity hashing, so the mixer is not optional. - Group index = the high bits:
h >> (64 - log2(G)). No modulo needed. - Tag = the low 7 bits:
h & 0x7F.
Using disjoint bit ranges keeps the two independent, so a tag match is a roughly 1/128 false-positive filter before any key is read.
Lookup within a group
- Load the 16 tag bytes.
- Compare to the broadcast tag (
_mm_cmpeq_epi8) and extract a 16-bit mask withmovemask. - Iterate set bits with
ctzandmask &= mask - 1, comparing the full key for each. - Compare the same tags against EMPTY. If any slot is empty, the key is absent and the search stops.
This yields about one well-predicted branch per group rather than one per slot.
Probe sequence and load factor
- Triangular probing across groups:
g, g+1, g+3, g+6, ...masked withG-1. For a power-of-two group count it visits every group exactly once and avoids the primary clustering of plain linear probing, while the in-group scan stays contiguous. - Max load around 0.875 (14 of 16 slots). Because each probe step examines 16 slots in parallel, the table tolerates a load that would ruin scalar linear probing (which wants roughly 0.5-0.7). Expected cost is about one group for hits and slightly more for misses.
Latency hiding: batching and prefetch
A lone lookup is latency-bound; a batch can be bandwidth-bound.
- Pass 1: hash every key in the batch (vectorizes cleanly) and store group indices.
- Pass 2: while probing key
i, issue__builtin_prefetchfor the tag line, and optionally the key line, of keyi + D. - Choose
D(typically 8-16) so thatD x work-per-proberoughly equals memory latency.
This converts serial misses into overlapped ones and commonly gives 3-5x on tables larger than the last-level cache. More advanced variants interleave state machines (AMAC) or coroutines.
Correctness argument
Insert places a key in the first group on its probe path with a free slot. Groups only fill, never empty (no deletions). So every earlier group on that path was full at insert time and remains full. Therefore a lookup that reaches a group containing an empty slot without a match can conclude the key is absent. Tags are only a filter: every tag hit is confirmed with a full key comparison, so false positives never produce wrong answers.
Complexity
- Time: expected O(1), about 1-2 group probes at load <= 0.875 with a good hash. Worst case O(G) under adversarial keys.
- Space: (1 + key + value) bytes per slot, with capacity at least n / 0.875 rounded up to a power of two. Overhead is 1 byte per slot versus 8-16 bytes of pointers per entry for chaining.
Sketch
GROUP, EMPTY = 16, 0x80
def lookup(table, key):
h = mix(key)
g = h >> table.shift # group index from high bits
tag = h & 0x7F # fingerprint from low bits
for _ in range(table.n_groups):
base = g * GROUP
tags = table.tags[base:base + GROUP]
for j in matches(tags, tag): # SIMD cmpeq + movemask in C
if table.keys[base + j] == key:
return table.vals[base + j]
if any_empty(tags): # SIMD cmpeq against EMPTY
return None
g = (g + step(_)) & table.group_mask # triangular: +1, +2, +3, ...
return None
Trade-offs
- Deletions: need tombstones plus periodic rehash; the early-exit invariant above assumes none.
- Resizing: doubling and reinserting is expensive, so in a kernel size the table up front from the known key count.
- Memory: a high load factor saves space but lengthens miss probes; 0.875 is a tuned compromise, not a law.
- Adversarial input: a fixed hash can be attacked; use a seeded hash if keys are untrusted.
- Portability: the SIMD path needs SSE2/NEON; provide a scalar fallback (SWAR with 64-bit words works well).
Validation and profiling
- Correctness: differential-test against a reference map using random, sequential, strided and duplicate-heavy keys; include tables at exactly the maximum load and a one-group table.
- Edge cases: with one group, the shift is 64, which is undefined behavior for
h >> 64in C, so special-case it. - Performance: microbenchmark across table sizes that fit in L1, L2, LLC and DRAM, for hit-only, miss-only and mixed workloads. Use
perf statto read cache-miss, branch-miss and IPC counters. Sweep the prefetch distanceDand the load factor, and confirm that gains vanish when the table fits in cache (where prefetching only adds instructions).
Common mistakes
- Choosing chaining or
std::unordered_mapand ignoring pointer chasing. - Using
h % capacityon a non-power-of-two capacity in the hot path. - Taking the index and tag from overlapping bits, which correlates them and inflates false positives.
- Forgetting alignment, so groups straddle cache lines.
- Prefetching too late or too early, and benchmarking only on cache-resident tables.