LIVE SUBMISSIONS — 3 DAYS

The Perfect Hash Function Came Last. Your Symbol Table Is Too Small for It.

Published: October 10, 2026 | Benchmarking & Profiling CPU & Microarchitecture Data Structures & Algorithms


The Perfect Hash Function Came Last. Your Symbol Table Is Too Small for It.

Two hundred and fifty-six tickers, packed eight bytes each, mapped to an instrument index. The lookup you would write if you had read the paper that went to ESA this year — a cache-resident k-perfect hash function routing every key to one 64-byte bin, one SIMD compare, no branches, "one cache miss for positive and negative queries alike":

inline bool find(uint64_t key, uint32_t& out) const {
    uint64_t kh  = (key ^ seed) * 0x9E3779B97F4A7C15ULL;          // one multiply
    uint32_t b   = fastrange(kh, nb);                              // bucket = high bits
    uint32_t bin = fastrange((kh ^ pilot_mul[pilots[b]]) * C, B);  // pilot byte -> bin
    const uint64_t* p = &bins[bin * 8];                            // one 64-byte line
    __m256i k4 = _mm256_set1_epi64x(key);
    unsigned m = _mm256_movemask_pd(_mm256_castsi256_pd(_mm256_cmpeq_epi64(_mm256_loadu_si256((const __m256i*)p), k4)))
               | _mm256_movemask_pd(_mm256_castsi256_pd(_mm256_cmpeq_epi64(_mm256_loadu_si256((const __m256i*)(p + 4)), k4))) << 4;
    out = vals[bin * 8 + (m ? __builtin_ctz(m) : 0)];              // branchless select
    return m != 0;
}

On an isolated Zen 2 core (aorus, Threadripper 3960X, clang 20, -O3 -march=native) that costs 12.4 ns per dependent lookup above the harness floor. boost::unordered_flat_map<uint64_t, uint32_t> with default everything: 6.6 ns. absl::flat_hash_map: 6.7. ankerl::unordered_dense: 7.7. A minimal-perfect-hash-style 1-PHF built with the same pilots and no bins at all: 7.1. Same ordering under gcc 14, on a Comet Lake i7 with gcc 16, and on an Apple M2. On the throughput side the plain 1-PHF is the fastest thing we measured at every size up to a quarter-million keys, and the k-PHF is three times slower than it.

The paper is right. Its speedup lives at 30 million keys, and it says so. This piece is about the sizes a trading system actually has — 32 to 512 instruments, a hundred FIX tags, ten thousand symbols in a bad month — and what wins there, measured against the maps you already link, plus the dumb structures everybody forgets to try. It is also about the benchmark we had to throw away three times before these numbers were real, because the third version was the one where the branch predictor had memorised our query stream and made a switch statement look like the fastest lookup on the board.

Where the claim comes from

"Non-minimal k-perfect hashing: Tight lower bounds and an application to fast static hash tables" (Groot Koerkamp, Hermann, Sanders, Walzer, arXiv 8 July 2026, accepted to ESA 2026). A minimal perfect hash function maps n static keys to n slots without collisions. Generalise twice: allow k keys per bin (a k-PHF), and allow spare capacity (load factor α < 1). Their theory result: combining the two collapses the space needed — for (k, α) = (16, 0.8) the lower bound is 0.027 bits per key, 8x less than exactly-full 16-bins and 32x less than a 1-PHF at α = 0.8. Their systems result: a k-PHF built on PtrHash whose static hash set is "consistently at least as fast as other hash sets for negative and mixed queries", and on two of three architectures "up to 1.5x speedup for large n ≥ 30M where a 1-PHF does not fit in cache."

That last clause is the whole thing. The k-PHF's advantage is that its routing table (one byte per bucket of several keys) is tiny, so it stays in cache when the 1-PHF's slot array does not. It is a large-n argument. Nothing in it says the structure is fast at 256 keys, and nothing in it compares against a general-purpose open-addressing map on a hot symbol table, which is the comparison an HFT reader would want. So we made it.

This is the constructive sequel to post #216, which ended on: your symbol table is not under attack, your FIX tag map has known keys, size the table right. Fine. The keys are known and static. Now what is the fastest thing to do with them?

What we built

Keys are 8-byte packed tickers — ESU6, AAPL, BRK.B, NQZ7, 1 to 8 characters, the way a hot-path symbol table stores them and the same packing post #225's FIX scanner used. Values are a uint32_t instrument index. A second key class, 133 real FIX tags (integers below 2048), for the one structure that only works on small integers.

Contenders, every one behind the same bool find(uint64_t, uint32_t&) const:

  • std::unordered_map, the baseline nobody should be using;
  • absl::flat_hash_map, boost::unordered_flat_map (1.86), ankerl::unordered_dense::map (4.5) — default hash, reserve(n), insert;
  • 1-PHF: our own PtrHash-style construction, α = 0.8, one 8-bit pilot per ~3 keys, key slots plus a separate value array; and an interleaved variant with 16-byte (key, value) slots;
  • k-PHF: the paper's structure, our own construction, α = 0.8, 8-key bins in 64-byte-aligned lines plus a value array (their static set with values bolted on); and a 4-pair variant with four (key, value) pairs in one line, so a lookup touches exactly one line;
  • sorted array + branchless binary search; scalar and 4-wide SIMD linear scan; a generated switch (key) { case 0x…: … }; a direct-index array for the FIX tags;
  • and a null contender that does no lookup at all — it returns a value derived from the key so the dependent chain still depends on it. That is the harness floor, and every number below has it subtracted.

Not the paper's Rust code. Ours is ~150 lines of C++ so that every instruction on the lookup path is visible; where the paper's PtrHash pays a multiply, so do we. Construction is the greedy version, buckets largest first, 8-bit pilots, restart on failure, no eviction:

// keys already hashed once: kh[i] = (keys[i] ^ seed) * C1; bucket = high bits
for (uint32_t b : buckets_largest_first) {
    for (uint32_t pilot = 0; pilot < 256; ++pilot) {
        bool ok = true; tmp.clear();
        for (uint32_t i : bucket_keys[b]) {
            uint32_t bin = fastrange((kh[i] ^ pilot_mul(pilot)) * C2, B);
            int dup = 0; for (auto t : tmp) dup += (t == bin);
            if (fill[bin] + dup + 1 > K) { ok = false; break; }   // bin would overflow
            tmp.push_back(bin);
        }
        if (!ok) continue;
        place bucket_keys[b] into their bins; pilots[b] = pilot; break;
    }
    if no pilot worked: new global seed, start over
}

The 1-PHF is the same loop with K = 1. Every table is verified against generator ground truth for every present key and 65,536 absent keys before it is timed.

Two access patterns, because they answer different questions:

// dependent: the next query depends on this lookup's result (latency)
uint64_t x = SEED;                                   // xorshift64 stream
for (i = 0; i < LOOKUPS; ++i) {
    bool f = find(Q[idx], v);
    uint64_t r = f ? v : 0x9E37;
    sum += r;
    idx = (r * 0x9E3779B1ULL + xorshift(x)) & mask;  // result + fresh randomness
}
// independent: random queries, results summed (throughput)
for (i = 0; i < LOOKUPS; ++i) { bool f = find(Q[xorshift(x) & mask], v); sum += f ? v : 0x9E37; }

The dependent chain is what a per-message hot path sees — you cannot start the next symbol lookup until this one has told you which book to touch. The xorshift in both loops is not decoration; the section after next is about what happened without it. The query array is clamp(4n, 2048, 2^20) entries, so at HFT sizes it lives in L1 next to the table and the chain measures the table, not the fetch of the next query. Two mixes: 100% hits (a symbol table on a feed) and 50% misses (an "is this in my universe" filter, the paper's negative-query case). Sizes 16 to 4M keys; 2^20 lookups per sample, eleven samples, medians. Isolated cores on aorus (Zen 2, clang 20 and gcc 14) and an i7-10700K (Comet Lake, gcc 16), plus an unpinned Apple M2 (clang 21). The Zen 5 machine was dropped: its amd-pstate powersave governor held the pinned core at 2.4 GHz and every number came out 1.8–2.5x high and unstable; a latency benchmark at the 5-nanosecond scale does not survive that.

At the sizes you actually have, the perfect hash comes last

Median ns per lookup above the 2.6 ns floor, dependent chain, 100% hits, aorus Zen 2, clang 20:

contender 32 keys 128 256 512 1024
boost::unordered_flat_map 6.5 6.7 6.6 6.6 7.9
absl::flat_hash_map 6.7 6.7 6.7 6.8 8.4
1-PHF (α=0.8) 7.0 7.0 7.1 7.1 8.1
ankerl::unordered_dense 7.8 6.4 7.7 7.5 9.7
1-PHF, key+value interleaved 7.7 7.7 7.7 7.7 9.0
k-PHF, 4 (key,value) bins 11.3 11.3 11.3 11.3 12.6
k-PHF, 8-key bins 12.4 12.4 12.4 12.4 13.5
sorted + branchless bsearch 9.6 13.4 15.2 17.0 19.7
SIMD linear scan 10.4 16.0 22.3 34.8 59.9
switch/case 15.4 19.8 22.6 25.4 29.2
std::unordered_map 13.7 14.2 16.3 14.5 17.8

Dependent-chain latency vs table size, ns above floor: boost, absl, the 1-PHF and ankerl within a nanosecond of each other; the k-PHF 1.7x behind until the table leaves cache

Read the two k-PHF rows against the four above them. At every size from 16 to 1024 keys the paper's structure is the slowest hashed lookup on the board — 1.7x boost and absl, 1.6x the 1-PHF built from the same pilots. gcc 14 says the same (10.6–11.3 vs 6.3–6.6 at 256), so does the Comet Lake (9.0–9.6 vs 5.3–6.3) and the M2 (16.1 vs 7.5–10.1). And the four general structures above it sit within one nanosecond of each other, which is the other half of the result: at 32–512 keys, boost::unordered_flat_map, absl::flat_hash_map, ankerl and a perfect hash are the same speed on the latency path. There is nothing to win here by being clever about hashing.

Note what does not appear on that table: the cache miss. Every structure here fits in L1 with the query array beside it. The paper's cost model, in which the k-PHF wins because it touches one line and the alternatives touch two or three, has no purchase when there are no misses to save. Something else is setting the price.

It is the length of the chain

perf stat on aorus, 256 keys, dependent chain, per lookup, harness floor included (the null row is the floor):

structure instructions cycles branch mispredicts /1000
null (floor) 16 11 0
boost::unordered_flat_map 45 39 44
absl::flat_hash_map 49 39 9
1-PHF 34 41 0.1
ankerl::unordered_dense 40 43 615
1-PHF interleaved 40 44 0.1
k-PHF, 4-pair bins 47 63 0.1
k-PHF, 8-key bins 47 66 0.2

The 1-PHF executes the fewest instructions of anything and lands mid-pack on cycles; the k-PHF executes about as many as boost and takes 24 more cycles per lookup than anyone. In a dependent chain, cycles per lookup is the length of the serial dependency from "key arrives" to "value available", and the k-PHF's is simply longer. Walk it. Both PHFs pay: multiply → fastrange (another multiply) → load the pilot byte → XOR, multiply → fastrange → load. The 1-PHF is then done: the key compare and the value load both depend only on the slot index and issue in parallel. The k-PHF, having loaded its 64-byte bin, must compare eight lanes, movemask, tzcnt, and only then knows which value to load — a compare-then-select stage of ~20 cycles on Zen 2 that sits squarely on the critical path, because which slot in the bin holds your key is information the structure does not have until it looks. The "one cache miss" design buys that miss with a longer chain, and at L1 scale the chain is all there is.

The 4-pair variant, values inside the bin, saves a load and about four cycles. It does not change the picture.

Then there is ankerl, which mispredicts a branch on 61% of lookups — its probe loop guesses "found in the first slot", and with unpredictable keys it is wrong most of the time — and still lands within four cycles of boost on the latency path, because a mispredict that resolves as soon as the compare completes costs about what absl's SIMD group probe costs anyway. That is a fact about 256-key tables in L1 and it does not survive the next section.

Throughput is a different race, and the 1-PHF wins it

Independent lookups, results summed, ns above the 1.6 ns floor:

contender 32 256 1024 4096 65k 262k
1-PHF (α=0.8) 0.9 0.9 1.1 1.3 3.9 8.9
absl::flat_hash_map 1.2 1.2 1.5 1.8 5.0 18.6
boost::unordered_flat_map 1.4 1.9 1.8 2.2 5.2 16.9
1-PHF interleaved 1.5 1.5 1.7 1.8 4.7 12.1
k-PHF, 8-key bins 2.6 2.6 3.0 3.6 7.8 13.5
k-PHF, 4-pair bins 2.9 2.9 3.2 3.4 6.9 14.7
ankerl::unordered_dense 6.5 5.7 5.7 5.6 8.4 19.9

Independent throughput vs table size, ns above floor: the 1-PHF leads at every size, absl second, the k-PHF pays for its bin compare and ankerl for its mispredicts

When the out-of-order core can overlap lookups, what matters is instruction count, branch behaviour, and how little of the machine each lookup occupies. The 1-PHF's 34 instructions with no branches win at every size, hit or miss, on every compiler and machine we ran — under gcc 14 it is 0.5 ns above floor, a third of absl; on the M2 0.2. Which is the honest case for a perfect hash on a hot table: not latency, where a good map is the same chain length, but throughput on a batch — a snapshot decoder walking a thousand symbols, a reconciliation pass — where 0.9 against absl's 1.2 is 25%, and against boost beyond 1k keys is 2x. The k-PHF is 3x behind the 1-PHF here; the extra vector work costs issue slots whether or not anything is waiting on it. And ankerl's 61% mispredict rate, harmless in the chain, is fatal in a loop: 5.7 ns, six times the 1-PHF and the worst hashed structure on the board.

The benchmark that fooled us, and the switch statement it made look fast

An earlier version of the dependent loop chose the next query as a pure function of the previous result and the loop counter — idx = (idx + 1 + (r + i) * C) & mask — over a 2048-entry query array. It is deterministic; we thought that was fine. It is also a walk over a state space of 2048 slots × 2048 loop phases, and a modern branch predictor with a long global history does not need the sequence to be short: it needs each branch's outcome to be a function of the recent branch history, and in a deterministic walk over four million states, the last few dozen branch outcomes identify where you are. It learned our query stream. Under that harness a generated switch over 32 keys took 0.011 mispredicts per lookup and came out at 2.3 ns above floor under gcc 14 — the fastest lookup on the board — and ankerl's probe loop mispredicted 0.1% of the time and won latency at every size to 512. Same code, same tables, wrong conclusion.

Feed both loops from a 64-bit xorshift instead (2^64 states; the recent history identifies nothing) and:

aorus, clang 20, 32 keys learnable walk xorshift
switch: mispredicts / lookup 0.011 2.47
switch: cycles / lookup 22 77
ankerl: mispredicts / lookup 0.001 0.70
ankerl: cycles / lookup, dependent 30 44
ankerl: cycles / lookup, independent 8 35
absl / 1-PHF: cycles, dependent 40 / 41 40 / 41

The branchless structures did not move; the branchy ones tripled. Every number in this article comes from the xorshift harness. Two things follow for the reader. First, if your lookup benchmark replays a fixed query sequence — and most do — a branchy structure's numbers are the branch predictor's numbers, not the structure's; anything with a data-dependent branch on the key (switch, binary search, linear scan, a Robin-Hood probe) is suspect until you have looked at its mispredict counter. Second, real feed traffic is neither a fixed sequence nor uniform noise — it has hot symbols and bursts — so the truth for your parser lies between the two columns, and only the right column is a lower bound you can trust.

With random keys the compiler's own perfect hash — the switch — is 15–29 ns above floor at 32–1024 keys, 2–3 mispredicts per lookup, the slowest thing here after std::unordered_map. Sorted + branchless binary search is 9.6 at 32 keys and grows with log n; the SIMD linear scan 10.4 at 32. Neither beats a hash at any size we tried, including 16 keys. The folklore that "below N keys, just scan" is, at least for uniformly random lookups on these cores, wrong from N = 16 up.

Misses, where the paper says the k-PHF shines

Fifty percent of queries absent, dependent chain, ns above floor at 256 keys: ankerl 5.3, 1-PHF 7.0, boost 7.6, absl 7.8, k-PHF 11.2–12.3.

ankerl gets faster on misses — its probe stops as soon as the stored distance says the key cannot be further on, and the mispredict it takes on a hit it does not take on a miss. boost and absl get a nanosecond slower (a 50/50 mix defeats the found/not-found branch in the harness, and a full first group sends the probe to a second). Nothing about a miss is cheaper for a perfect hash: bucket, pilot, slot, compare, the same chain as a hit, and only then "no" — but nothing is more expensive either, and at 7.0 the 1-PHF is now second. The k-PHF, flat at 11–12, is still last. The paper's "at least as fast on negatives" is, again, a statement about large tables where the general maps' probes wander across lines; at 256 keys the wandering is inside one L1 line and stops early.

For integer keys, do not hash at all

The key class that is small integers — FIX tags, message types, venue codes — wants none of the above:

// direct index: one load; the range check and the sentinel compare are branch-free
uint32_t x = tbl[key & (limit - 1)];   // limit = next power of two above the max tag
v = x;
return (key < limit) & (x != SENTINEL);

133 FIX tags: 1.9 ns above floor dependent, 0.2 ns independent, versus 6.4 / 1.5 for boost, 6.7 / 1.2 for absl and 7.1 / 0.9 for the 1-PHF. A 2 KB array (tags below 512) or 8 KB (below 2048), one load, no hash. If your FIX decoder hashes tags, that is the cheapest 3x on the parse path you will find this year.

Where perfect hashing pays: when the table leaves cache

Now the paper's regime, or as close as a 64 GB desktop gets. Dependent chain, 100% hits, ns above floor (the floor itself is 14.7 ns here — the 8 MB query array):

keys boost absl ankerl 1-PHF 1-PHF interleaved k-PHF 8-key k-PHF 4-pair
64k 17.0 21.0 25.1 17.9 17.2 28.6 21.0
1M 136.2 143.1 210.9 117.5 110.4 144.4 112.0
4M 190.6 227.3 277.8 191.0 161.6 271.1 162.6

1M to 4M keys: the interleaved 1-PHF and the 4-pair k-PHF tie and lead; the k-PHF with a separate value array trails absl

Three things happen once nothing fits.

First, perfect hashing wins, by about what the paper says: the 4-pair k-PHF at 4M keys is 28% under absl, 15% under boost, 41% under ankerl, on Zen 2; 27% and 12% under absl and boost on Comet Lake; 23% and 12% on the M2. And the interleaved 1-PHF is identical to it — 161.6 vs 162.6 ns on Zen 2, 97 vs 99 on Comet Lake, 106 vs 112 on the M2. So the mechanism is not the k-bin. It is footprint and layout: 15–20 bytes per key against 32–34, and key and value in the same line. The paper's k-PHF-specific advantage — a pilot table 8–30x smaller than a 1-PHF's — only bites when the pilot table leaves cache, and at 4M keys every pilot table we built (0.25–0.35 bytes per key, ~1.4 MB) still sits in L2 on both x86 machines. Their 30M threshold is where that stops being true. Below it, an interleaved 1-PHF gets you the whole large-n win with a shorter lookup chain.

Second, layout is a bigger lever than the hashing scheme. Same pilots, same bins, same hash: the k-PHF with values in a separate array is 271 ns at 4M, with values in the bin 163 — one line per lookup instead of two. And the plain 1-PHF with its separate value array (191) is only level with boost.

Third, on misses the SIMD maps take it back: at 4M with 50% absent, absl is 93 ns above floor, boost 100, ankerl 103, the interleaved PHFs 138–139. The group they fetched contains its own empty slot; the PHF has to fetch the slot to learn it is empty. The paper's negative-query claim is about sets compared against other sets at 30M keys; a map with a SIMD group probe is a different opponent.

Footprint in bytes per key at 4096 keys

Construction, briefly

At α = 0.8 the greedy builder places every k-PHF on the first attempt at every size up to 4M keys (0.6 s at 1M, 8-bit pilots, no eviction), and the 1-PHF at λ = 3 keys per bucket likewise. Exactly full bins (α = 1.0) are another matter: 1–9 attempts up to 4k keys, then failure at 16k and beyond — greedy placement cannot fill bins exactly without the eviction machinery PtrHash carries, which is why the paper needed it. At 256 keys any of these builds in 10–30 microseconds, so "build cost" is not a consideration at HFT sizes; at 30M keys it is the paper's business.

One construction bug is worth writing down because it will bite anyone reimplementing this from the paper. The bucket is taken from the high bits of the key hash, so keys sharing a bucket have similar high bits. If the slot is then fastrange(kh ^ pilot_hash), which also reads the high bits, XOR-ing in a pilot moves all of a bucket's keys together and never separates two that collided — our first 1-PHF failed to build past 64 keys. One diffusing multiply after the XOR ((kh ^ p) * C before the fastrange) fixes it, and PtrHash pays that multiply too.

Methodology, and the six things we got wrong first

Everything is in experiment/: a CMake project that fetches abseil 20250127.1, Boost 1.86 (unordered only) and unordered_dense 4.5.0, so the same binary builds on every machine; phf.h with both PHFs; bench.cpp with verify/sweep/tags/footprint/single modes; run.sh. Isolated cores on aorus (18) and intel (6), -O3 -march=native, eleven samples, medians. The null contender is subtracted from every reported number and its raw value is stated.

We threw away three complete sweeps before the reported one. The first version used a fixed 2^20-entry query array — 8 MB — so every step of the "dependent" chain paid an L3 fetch for the next query, and std::unordered_map came out level with absl. The second used a 4096-entry minimum, which is 32 KB, which is Zen 2's L1D, so the query array evicted the table it was querying. The third had the learnable walk described above, and produced a switch statement that beat every hash map. The 64-byte bins were 16-byte aligned (std::vector), so every "one-line" bin was two. The perf harness's checksum was unused, so the compiler removed the lookup loop and reported fifteen trillion lookups a second. And our first PHF hash chained six multiplies where PtrHash uses two, which made the perfect hash look 2x worse than the general maps before it looked 1.7x worse — the difference between an implementation finding and a structural one. Each of these produced numbers that looked like findings.

What to do with this

The perfect hash is not the answer at HFT table sizes, and neither is anything clever.

  • Small integer keys (FIX tags, message types, venue codes): a direct-indexed array. 1.9 ns dependent, 0.2 ns throughput, nothing else is within 3x.
  • 32–512 symbols on the latency path: it does not matter. boost, absl, ankerl and a perfect hash are within a nanosecond; take boost::unordered_flat_map (6.6 above floor, and the best of them at every larger size too), or absl if it is already in the build. Do not reach for a switch, a sorted array or a linear scan on the strength of a benchmark that replays queries: with unpredictable keys they are 1.5–4x slower than any hash from 16 keys up.
  • Batch throughput over a static table, or anything from 4k to 250k keys: a 1-PHF. 0.9 ns above floor at every size to 4k, hit or miss; 34 instructions and no branches; builds in microseconds. Absl is 25% behind it, boost 2x beyond 1k keys, and ankerl 6x — do not put ankerl in a loop over random keys.
  • A static table that does not fit in cache (millions of keys — a full reference-data universe, an order-ID map after recovery): an interleaved 1-PHF, key and value in one line — 28% under absl at 4M on Zen 2, 27% on Comet Lake. The k-PHF from the paper ties it there and pulls ahead only when the pilot table itself outgrows cache, which their measurements put at 30M keys.
  • The k-PHF at 256 keys: no. It is a beautiful piece of theory that buys one saved cache miss with a longer instruction chain, and at the sizes where a trading system's tables live there is no miss to save.
  • Any lookup benchmark: subtract a null contender, drive the queries from something the branch predictor cannot learn, and read the mispredict counter before you believe a branchy structure's number.

Review quiz

Pass it to mark this article as read and count it toward your reading achievements.

Five questions about this article. Get four right and it counts as read. Review quizzes come with a membership.

Log in See membership

Back to Courses
660 reads 1

Comments

No comments yet. Be the first to share your thoughts.

Log in as a member to comment, or subscribe to join the discussion.