r/cpp • • Sep 19 '26
A clever branch free optimization
I'm the developer of memlz which is an extremely fast compression library.
We have char* src, char* dst for the source and destination buffers and uint16_t flags that we prepend bits to one at a time. The inner core looks something like this (pseudo code):
flags <<= 1;
uint64_t payload = ((uint64_t*)src)[i];
uint16_t hash_index = hash_function(payload);
if (hash_table[hash_index] == payload) {
flags |= 1;
*(uint16_t*)dst = (uint16_t)hash_index;
dst += sizeof(uint16_t);
}
else {
*(uint64_t*)dst = payload;
hash_table[hash_index] = payload;
dst += sizeof(uint64_t);
}Depending on a hash comparison we need to output either 2 or 8 bytes, advance dst accordingly and prepend either a 1 or a 0 to flags.
Furthermore, at the end it's required that hash_table[hash_index] == payload, so we update hash_table in the false-case.
Let's benchmark it with 211 MB input so it's uncached:
memlz: 2744 MB/s
Now let's look at an amazing idea. The output to *dst can be rewritten with the ternary operator:
*(uint64_t*)dst = hit ? hash_index : payload;
That turns into a compare instruction (cmp) and a conditional move instruction (cmove) with no branching:
00007FF742A5A55B mov rax,r10
00007FF742A5A55E cmp rcx,r10
...
00007FF742A5A56D cmove rax,rdx
00007FF742A5A571 mov qword ptr [rdi],raxThe advancement of dst is also simple to make branchless, noting that hit will turn either 0 or 1:
uint64_t hit = (hash_table[hash_index] == payload);
dst += 8 - (hit * 6);Now look at updating the hash_table where we update it to payload only if it differed from payload. What we can do is update it unconditionally at the end, and hope that the extra number of unnecessary writes to memory (where it just overwrites the same value) are not too expensive.
Final branch-free version:
uint64_t payload = ((uint64_t*)src)[i];
uint16_t hash_index = hash_function(payload);
flags <<= 1;
uint64_t hit = (hash_table[hash_index] == payload);
flags |= hit;
*(uint64_t*)dst = hit ? hash_index : payload;
hash_table[hash_index] = payload;
dst += 8 - (hit * 6);Let's benchmark it:
memlz: 4269 MB/s
I had never believed such gains were possible because I had been micro-optimizing on this for weeks.
I later achieved 5070 MB/s. To put it in perspective, uncached memcpy runs at 14000 MB/s here and LZ4 - another popular fast compression library - at 718 MB/s.
[EDIT: The unaligned memory reads and writes are UB. For the dst write can simply declare uint64_t hash_index and use memcpy() which the compiler optimizes into the same binary code]
[EDIT: 19 days after I'm at 6304 MB/s]
View all comments
Show parent comment
2
u/ReDucTor Game Developer | quiz.cpp-perf.com Sep 22 '26 edited Sep 22 '26
That really depends on how you implement it, if you default to there being 4 chunks and they all share the same hash map then your only losing a couple of bytes on the boundaries to align them. However it does imply that you can more easily define chunks ahead of time (I did come up with an idea at the end of this comment)
Your updating the hash table even when there is no a hit with the value, so if you have a hash collision (e.g. 2 and 46370) then the last one will be what is stored in the final hash table. You probably want to do hash_table[hash_index] = hit ? ... (fixing this also now means your store has a 2 chained load dependency not just one, so slightly slower, but no collision bug)That hash function seems like it would have poor Avalanche behavior which you might not want for a generic input the lower bits will have significantly more impact then the higher bits you could probably test this and see the impact with a file where you generate output that is random for the upper 8-bits and compare it with random for the lower 8-bits, the one just changing the upper-8 bits will likely have significantly worse compression (estimating ~4x worse)
I did a bit of quick google to find the repo, here a few other thoughts:
As a completely crazy idea, you should be able to calculate the absolute best case for compress (2 + len/2) which means you could have two destination pointers, one which goes forward and one which goes backwards, alternate each byte between the forward and backwards pointers, have a basic branch that checks when they overlap and as soon as this happens then start from after that best case compression pointer (where it starting going backwards) and do the rest going forward. This would break the long
dstandflgdependency chains in two hopefully allowing for a good performance improvement.EDIT: Instead of "do the rest going forward" you could repeat with the remaining byte count and do the same best case repeating until a desired lower bound