11 Nanoseconds per Word: Over-Optimizing Anagrams
David G. Andersen optimizes a Rust anagram solver from 173 down to 10.9 nanoseconds per word using custom corpus-tuned 64-bit prime products and CPU vectorization.
read it A thorough, step-by-step performance optimization breakdown that offers great insights into low-level Rust engineering and clever data representation.
summary
Writing a word-ladder solver in Rust, the author iteratively optimizes anagram dictionary generation from 173 nanoseconds per word down to 10.9 nanoseconds. The progression covers removing string allocations, packing letter counts into u128s, switching hash maps, and designing a custom 64-bit Gödel numbering scheme with tuned primes for the Scrabble dictionary. Final speedups leverage instruction-level parallelism, fixed-length loops, and auto-vectorization.
key points
- Naive sorted-string approaches and vector allocations yield a baseline of 173ns per word, taking 31ms total for a 178k-word dictionary.
- Replacing string keys with a 64-bit Gödel numbering scheme using corpus-tuned primes prevents integer overflow while guaranteeing unique collision-free keys.
- Low-level techniques including dual-accumulator instruction-level parallelism, branchless loops, and auto-vectorization drive performance down to 10.9ns per word.
who should read it
Systems programmers, Rust developers, and performance optimization enthusiasts.
discussion warm
If the dictionary is static what's the point of building a hashtable out of it at runtime? If it's not how do we know this'll work with a different dictionary? I didn't know about Gödel numbering though, that part is cool.
Questioning why a static dictionary needs to be built at runtime introduces a practical deployment consideration.
Generated by an LLM from the article and thread. Check the sources before relying on it.