Billion-query-per-second lookup tables in C++

24 points by signal-11


pervognsen

For the article's key set {"GET", "POST", "PUT", "DELETE", "PATCH"} you can use the perfect hash function (0x13340001u * (n ^ s[0])) >> 29 into {0, 1, ..., 7}, assuming the length n is provided with s and s[n] is 0 (so that unconditionally indexing s[0] gives a well-defined value).

That's 5 cycles of latency on typical processors after s[0] is loaded. The article's (length + asso[key[i]] + ...) % table_size adapted to this example yields (n + a[s[0]]) & 7. The multiply-shift form is 1 cycle less than that on modern AMD (4 cycle L1 latency) and 1-2 cycles less on modern Intel (4-5 cycle L1 latency).

You can probably do even better.

gignico

Reading past the end of a buffer is fine as long as you do not cross into another memory page, and pages are at least 4 kilobytes.

No, reading past the end of a buffer is UB no matter what.