Many programs repeatedly map a small, fixed set of strings - such as HTTP methods, protocol names, or compiler keywords - to values. A conventional C++ unordered_map handles these lookups at runtime by hashing the full string and navigating buckets, even though its keys never change. The proposed alternative is a perfect hash: a function tailored to the known keys so each one maps to a unique table slot, eliminating collisions, probing, and chains. The slot is calculated from the string’s length plus small values drawn from selected character positions, then reduced with a bit mask. For GET, PUT, POST, and DELETE, for example, using the first character can assign each key a distinct slot. A lookup still compares the candidate string with the slot’s stored key, which also lets it reject unknown inputs.
A C++23 library performs the search for this hash function during compilation, using a bounded greedy algorithm that tries association values without revising earlier choices. This avoids a separate code-generation tool and leaves a constant map for runtime use; the hash calculation can require only a few instructions. The remaining cost is string equality. Rather than compare bytes one at a time with a branch per byte, the approach treats keys as vectors and aims to use processor vector operations on ARM and x64. The core argument is that fixed-key lookups can be much cheaper when both hashing and comparison are designed around the known set.
Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.