11 Nanoseconds per Word: Over-Optimizing Anagrams wiredream.com · 18 points · 3 ...
HN Best 200 @best
11 Nanoseconds per Word: Over-Optimizing Anagrams wiredream.com · 18 points · 3 comments · HN thread
TL;DR David G. Andersen writes up a Rust optimization exercise: building an anagram index over the 178,690-word Scrabble dictionary, which he was using as part of a solver for a Word Ladder variant that allows anagram moves. He cuts the build time from 31 ms (173 ns per word) to 1.96 ms (10.9 ns per word), about 15.8x, mainly by packing letter counts into a 64-bit prime-product (Gödel-style) key tuned so that no dictionary word overflows.
- Baseline builds a HashMap<String, Vec> keyed by sorted letters, taking 31 ms (173 ns per word).
- Replacing per-key Vec allocations with flat arrays and inline singletons drops the time to 20 ms.
- Packing 4-bit letter counts into a u128 and switching to FxHashMap brings it to 4.1 ms.
- A 64-bit product of letter primes, with the prime assignment tuned on the 15-letter words so nothing overflows, gives a collision-free key; the largest product, PSYCHOPATHOLOGY, uses about 63.9 bits.
- Final steps use 5-bit packed input, two independent accumulators, a fixed 16-character loop and auto-vectorization, reaching 1.96 ms; the author says this is close to the limit for a single core without explicit SIMD.
Discussion The thread is small, with three top-level comments. Most of the discussion is nostalgic and light: one commenter enjoys the post's aside that Knuth probably noticed the trick in 1965, and another recalls building anagram dictionaries for programming contests. The mood is friendly rather than critical, though one commenter questions the basic premise of building the index at runtime.
- The Knuth aside is the best part of the post (a few): One commenter finds the remark that Knuth probably noticed the technique in 1965 funny and humbling, suggesting it would work as a bumper sticker. Praise is for the writing tone rather than the optimization itself.
- Precomputing anagram groups into a static file is the better approach (a few): A commenter recalls precomputing anagram groups once into a sorted word list with offsets to the next anagram, so that searches for multi-word phrases only need to check subsets of letters. They describe this as an older contest-style technique.
- Runtime hash table is questionable if the dictionary is static (a few): One commenter asks why the dictionary is hashed at runtime if it never changes, and whether the prime assignment still works with a different dictionary. They find the Gödel numbering part interesting.
Links from the comments
#rustOptimization #anagrams #hashing #godelNumbering #wordLadder #performance