User Agents

Web browsers and everyday web tech, explained

Hash Table Collisions: Swiss, Robin Hood, CPU Cache

· 9 min read · Cookies and Cache

In this article
  1. Background: What a Hash Table Actually Does
  2. Collision Resolution: The Two Classic Approaches
  3. Robin Hood Hashing: Fairness in Probing
  4. Swiss Tables: SIMD and Metadata
  5. CPU Cache Lines: Why Memory Layout Matters
  6. How to Choose: Swiss vs. Robin Hood vs. Chaining
  7. Common Problems and Misconceptions
  8. Safety and Correctness Notes
  9. Alternatives and Future Directions
  10. Frequently Asked Questions

Hash tables collide because multiple keys can map to the same slot, and the way a hash table resolves those collisions—plus how it accesses memory—determines its speed. Swiss tables and Robin Hood hashing are two different collision-handling strategies, while CPU cache lines are the hardware reality that makes some strategies far faster than others. This article explains each piece and how they fit together.

Background: What a Hash Table Actually Does

A hash table stores key-value pairs in an array. When you insert or look up a key, the table runs a hash function to turn the key into an integer, then maps that integer to an array index (usually by taking the remainder after dividing by the array size). The problem: hash functions can produce the same index for different keys—that's a collision. If two keys land in the same slot, the table must decide what to do.

Collisions are unavoidable in practice because the number of possible keys vastly exceeds the array size. Even with a perfect hash function, once the table is more than about 70% full, collisions become frequent. The real design choice is how to handle them.

Collision Resolution: The Two Classic Approaches

There are two main families of collision resolution:

  • Separate chaining: each slot holds a linked list (or a small tree) of entries that collided. Insertion is O(1) on average, but following pointers is cache-unfriendly.
  • Open addressing: all entries live in the main array. When a slot is full, the table probes other slots according to a rule (linear, quadratic, or double hashing). No pointers, but the table must have spare slots.

Most modern high-performance hash tables use open addressing because it keeps data in contiguous memory, which is exactly what CPU caches like. But open addressing has a weakness: as the table fills, probes get longer, and performance degrades sharply. That's where Robin Hood and Swiss tables come in.

Robin Hood Hashing: Fairness in Probing

Robin Hood hashing is an open-addressing technique that reduces the variance of probe lengths. The idea: when you insert a key and find its slot occupied, you compare how far the existing key has already probed from its ideal slot (its "distance from home") with how far you've probed for the new key. If the existing key is closer to home, you swap—the new key takes the slot, and the old key continues probing.

This "steal from the rich, give to the poor" approach ensures that no key ends up extremely far from its ideal slot. The average probe length stays low, and more importantly, the worst-case probe length is bounded by O(log n) with high probability. That makes lookups more predictable, which is valuable for real-time systems or when you want consistent performance. However, Robin Hood hashing still uses a linear probe sequence, so each miss requires checking consecutive slots—which is cache-friendly but not as fast as it could be.

Swiss Tables: SIMD and Metadata

Swiss tables (the design behind Google's Abseil flat_hash_map and C++'s std::unordered_map in some implementations) take a different approach. Instead of storing just keys, each slot has a 1-byte metadata value that encodes the top 7 bits of the hash (plus a control bit). The actual key-value pair is stored in a separate parallel array.

When looking up a key, the table computes the hash, then uses SIMD (Single Instruction, Multiple Data) instructions to compare the metadata of 16 slots at once. For example, on x86, the _mm_cmpeq_epi8 instruction compares 16 bytes in one operation. This means the table can check 16 potential slots in the time a traditional table checks one. If the metadata matches, it then checks the actual key to confirm (since the 7-bit metadata is only a filter, not a full hash).

The key insight: the metadata array is small (1 byte per slot) and contiguous, so it fits in a single cache line for 16 slots. The CPU can load 64 bytes (a cache line) and compare all 16 metadata bytes in one go. This is why Swiss tables are so fast—they turn a sequential probe into a parallel SIMD comparison.

CPU Cache Lines: Why Memory Layout Matters

A CPU cache line is the smallest unit of memory that the CPU can load from RAM—typically 64 bytes on modern x86 and ARM processors. When the CPU reads any byte, it loads the entire 64-byte line into cache. If the next data you need is in the same line, it's already there; if not, you wait for a memory fetch (which can be 100+ cycles).

Hash table performance is dominated by cache misses. A traditional chained hash table stores keys and pointers scattered across memory, so each probe might require a separate cache line load. Open addressing keeps everything in one array, so consecutive slots are in the same cache line—but linear probing still checks one slot at a time. Swiss tables exploit the cache line by packing 16 metadata bytes into 16 bytes, so a single cache line load gives you 16 potential matches. This is why Swiss tables are often 2-3x faster than Robin Hood on lookups, despite both being open addressing.

However, cache lines also impose a constraint: if your keys are large (say, a 100-byte struct), the metadata array is still small, but the actual key data is spread out, and you'll miss the cache when you confirm a match. That's why Swiss tables store keys in a separate array—the metadata filter reduces the number of times you need to touch the larger key data.

How to Choose: Swiss vs. Robin Hood vs. Chaining

There's no single best choice; it depends on your workload:

  • Swiss tables are best for general-purpose use with small-to-medium keys (integers, short strings, pointers) where lookups dominate. They're the default in many modern C++ libraries.
  • Robin Hood hashing is better when you need predictable worst-case performance (e.g., real-time systems) or when you're implementing a custom table and can't rely on SIMD instructions. It also handles high load factors better than plain linear probing.
  • Separate chaining is still useful when keys are large and copying is expensive, or when you need to delete entries frequently without tombstones. But it's slower for cache reasons.

If you're on a platform without SIMD (some embedded CPUs), Swiss tables lose their main advantage. If your keys are huge (like long strings), the metadata filter saves time, but the final key comparison still costs. Measure with your real data.

Common Problems and Misconceptions

A common misconception is that Swiss tables eliminate collisions—they don't. They only make the probe faster by checking many slots at once. Collisions still happen; the metadata filter just reduces the cost of checking a wrong slot.

Another issue: both Swiss and Robin Hood tables use tombstones for deletion. When you delete a key, you can't just clear the slot, because that would break the probe chain for other keys. Instead, you mark it as deleted. Over time, tombstones accumulate and slow down lookups. Swiss tables handle this by occasionally rehashing, but if you delete and insert frequently, the table can degrade. Robin Hood hashing has a clever trick: when you delete, you can shift back subsequent entries to fill the gap, but that's complex to implement correctly.

Also, hash functions matter. A poor hash function can cause many collisions regardless of the collision strategy. Swiss tables use the top 7 bits of the hash as metadata, so a weak hash that produces similar high bits will cause false matches, slowing things down. Always use a good hash function (like wyhash or xxHash) for your data.

Safety and Correctness Notes

When implementing or using these tables, keep these in mind:

  • Never assume a hash table is thread-safe unless documented. Concurrent reads are usually safe, but writes require external locking or a concurrent design.
  • Be aware of hash-flooding attacks: if an attacker can choose keys that collide, they can degrade your table to O(n) per operation. Use a randomized hash seed or a cryptographic hash for untrusted input.
  • When using Swiss tables, ensure your SIMD code handles unaligned accesses correctly—most libraries do, but custom implementations can crash on some architectures.
  • For Robin Hood, the swap operation must be atomic if you're doing concurrent inserts; otherwise, you'll corrupt the table.

Alternatives and Future Directions

Beyond Swiss and Robin Hood, there are other modern designs:

  • F14 tables (Facebook's) use 14-way SIMD groups, similar to Swiss but with a different metadata layout that reduces memory overhead.
  • Hopscotch hashing uses a neighborhood of slots and a bitmap to find free slots quickly, offering good cache behavior with less SIMD reliance.
  • Cuckoo hashing uses two hash functions and kicks out existing keys to alternate positions, guaranteeing O(1) worst-case lookups but requiring more complex inserts.
  • Extendible hashing is for disk-based storage, not CPU cache, but it's worth knowing if you're working with large datasets.

The trend is toward SIMD-friendly metadata and cache-line-aware layouts. As CPUs gain wider SIMD units (AVX-512 has 512-bit registers), Swiss tables can check 64 slots at once, making them even faster.

Frequently Asked Questions

Why do hash tables have collisions at all?

Because the number of possible keys is infinite (or at least much larger than the array size), and a hash function maps many keys to the same index. Even with a perfect hash function, you'd need an array as large as the key space, which is impractical. Collisions are a mathematical certainty.

Is Robin Hood hashing faster than Swiss tables?

No, not in typical CPU-bound workloads. Swiss tables use SIMD to check multiple slots per instruction, which is faster than the sequential probing of Robin Hood. However, Robin Hood can be faster in specific cases where SIMD is unavailable or where the load factor is very high, because it keeps probe lengths more uniform.

What is a cache line and why does it matter for hash tables?

A cache line is the smallest block of memory a CPU loads from RAM, typically 64 bytes. If your hash table stores data in a contiguous array, a single cache line load can cover many slots, reducing memory latency. If your data is scattered (like linked lists), each probe may require a separate cache line load, which is slow.

Can I use Swiss tables in my own code?

Yes, if you're using C++17 or later, you can use std::unordered_map with the Abseil or F14 implementations, or include the Abseil library directly. For other languages, there are ports like swiss-table for Python or Rust's hashbrown which uses a similar design.

What's the best hash function for a Swiss table?

You want a fast, high-quality hash that produces well-distributed 64-bit values. Good choices are wyhash, xxHash, or MurmurHash3. Avoid simple hashes like modulo of a key, because they can produce patterns that cause many collisions in the top bits.

Do Swiss tables work well for string keys?

Yes, but the string itself is stored separately, and the metadata only covers the hash, not the string content. So lookups still require a full string comparison when the metadata matches. If your strings are long, the comparison cost can dominate, but the metadata filter still avoids many unnecessary comparisons.