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]
42
u/TheQuranicMumin Lang & Library contributer Sep 19 '26
With char* the store to *dst may alias hash_table and src, so it can't hoist the table load above the output store or keep the table base in a register across iterations. You could try "char* __restrict src, * __restrict dst" plus a __restrict table pointer to give the compiler an assurance.
23
u/Total-Box-5169 Sep 19 '26
Make sure your benchmarks are running with fixed CPU frequency to be able to do valid comparisons.
7
u/TheThiefMaster C++latest fanatic (and game dev) Sep 19 '26
Can't you do
*(uint64_t)dst = payload;unconditionally? In a hit the values are the same so you can just use payload again and that lets you remove the ternary.In the original you only output 2 bytes though - is the whole "trick" that you're relying on little-endian and being able to write off the end of dst by up to 6 bytes?
3
u/KAMEHAMEHAMEHAAAA Sep 20 '26
Is there any meaningful difference in throughput when compiling with
-march=native?2
u/ReDucTor Game Developer | quiz.cpp-perf.com Sep 21 '26
With your branch free code, you force two heavy-ish loop carried data dependencies, one is the loading from the source, the other is the load from the hash_table, and depending on the hash function you might have another heavy dependency if it does any expensive things like division or modulo.
Due to this you would probably get better performance if you split the data into chunks and do multiple in one loop, as enables the CPU to better take advantage of out of order execution when stalled on the loads. Plus if you scale up chunking you also have more room for using multiple threads.
Also your code does not handle hash collisions which means that you potentially will hit situations where the wrong data shows up in the decompressed file.
18
u/Gungan_Boss_Nass premature cleverization Sep 19 '26 edited Sep 19 '26
Here's an old trick we used to use on some platforms where no conditionals were branchless. It can still be used with complex conditionals and/or when your compiler isn't smart enough (e.g. with SIMD).
To simplify, let's say you have signed 32-bit integers with absolute values below the 2nd MSB, e.g. up to 0x3fffffff. Since your integers are two's complement, you can turn
a < binto a mask with(a - b) >> 31:becomes:
In trivial cases like this, it's more efficient to compute both the e/f and g/h subexpressions speculatively than to figure out which one you need first.
Edit: fixed missing ( typo.
10
u/slumberchum Sep 20 '26 edited Sep 20 '26
Nice, I enjoy reading these. I believe the branch-free version depends on little-endian byte ordering, FWIW, since the first 2 bytes of hash_index promoted to uint64_t will be 0 otherwise.
1
u/ImNoRickyBalboa Sep 20 '26
Unaligned stores are undefined behavior, and non portable. But whatever rocks your boat.
1
u/martinus int main(){[]()[[]]{{}}();} Sep 20 '26
thanks, interesting read! I had a look and threw the code in front of an AI to see if an SSE variant would help performance, and it came up with this. Highly untested, but the result on the benchmark is at least byte identical. https://gist.github.com/martinus/7137a10fec607e7fd0937094887dc672
Benchmarks from my Ryzen 9 7950X (Zen 4). Both builds
-O3 -msse4.1; the SSE build adds-DMEMLZ_SSE.2
u/Independent_Art_6676 Sep 23 '26 edited Sep 23 '26
I have frequently found that conditional branches slow the machine down, even with branch prediction. Removing them can be easy or off into the dark art voodoo stuff, but its often worth it in high speed areas. Most of what I do is numerical so I end up exploiting the 'cast to bool is a cast to 0 or 1' math and doing things like x+= (condition)*value; //adds value if true, else does nothing (adds 0). The addition of zero isn't free but an add of 0 is MUCH cheaper than branching to avoid a simple add... There are other ways to exploit it too, like turning conditions (via the 1s and 0s again) into lookups into small tables.
that to say, your hit variable ? operator MAY benefit from this kind of tweak to eliminate that conditonal if it jumps (if the compiler made it a table already or otherwise optimized it, no effect). Could try it to see? I think its just = hit*hash_inded + !hit*payload (but there may be a much better way to write that or put hit and payload into an array to index from so its = array[hit])
1
u/UndefinedDefined Sep 21 '26
Now think about AVX-512 and VPCOMPRESSB and VPERMB - your algorithm can be optimized to reach memory speeds basically.
-2
u/Both_Helicopter_1834 Sep 20 '26
Isn't there a reddit for the C language you can put this in?
-11
u/RadimPolasek Sep 19 '26
I can see a ternary operator so that's not a branch free...