Skip to main content

Module eq

Module eq 

Source
Expand description

Comparing two byte strings without leaving the function.

a == b on two slices ends up in the platform’s memcmp. That is the right answer for a megabyte and the wrong one for a key: a profile of SADD on the wire had seven percent of the command inside _platform_memcmp and the stub that reaches it, comparing nineteen bytes. The call itself, the length dispatch inside it and the return are most of that, and none of it is the comparison.

So this compares in machine words and stays inline. A key or a member is almost always shorter than a cache line, and the shapes that matter are the ones a benchmark and a real workload agree on: key:000000000001 at fourteen bytes, member:000000000001 at nineteen, a session id at thirty two.

§The last word overlaps

A comparison of nineteen bytes reads bytes 0..8, 8..16 and then 11..19, which covers the whole string with three loads and no tail loop. The middle five bytes are read twice, which costs nothing and is what keeps the shape branch free. Below eight bytes the same trick runs on four byte words, and below four it is a loop of at most three bytes, which is shorter than any cleverness would be.

§This is equality and not ordering

There is no cmp here on purpose. Nothing on the hot path needs to know which of two keys sorts first, and a word wise ordering would have to byte swap on a little endian machine to get the answer right, which is the sort of subtlety that is worth avoiding when nothing is asking for it.

Functions§

bytes_eq
Whether a and b hold the same bytes.