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],rax

The 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]

103 Upvotes

62 comments sorted by

View all comments

Show parent comment

10

u/Total-Box-5169 Sep 19 '26

In modern CPUs compilers optimize simple ternary expressions like that using a conditional move operation and that is branch free.

10

u/kvitterk Sep 19 '26

Replace the ternary with an if statement and I'm pretty sure it generates the same assembly as the ternary version.

2

u/DrShocker Sep 19 '26

Almost certainly. Assuming for a moment the compiler doesn't optimize out the branch, I would guess you could do something like

hash_table[hit * hash_index];

which should work, if you're able to offset the "actual" values of the table by 1 so that you can use zero in this way. But that's most likely fine.

-1

u/Total-Box-5169 Sep 19 '26

A ternary expression is far better to convey your intentions to the compiler when one needs branchless code, otherwise the compiler will have to do extra work to proof such optimization can be applied.

7

u/________-__-_______ Sep 19 '26

I believe most compilers treat them exactly the same, the compiler frontend just converts tenary expressions to if statements when emitting the SSA IR. That simplifies the backend, and makes any optimizations applicable to if statements as well.

2

u/v4lt5u Sep 20 '26

That's false, not sure why this keeps getting repeated https://godbolt.org/z/9b4nx5szf

1

u/Som1Lse Sep 21 '26 edited Sep 21 '26

It's only somewhat false, but that's a pedantic nitpick. Your statement is still ultimately correct in practice.

Edit: When both branches compute a value it is just true.

1

u/DrShocker Oct 03 '26

Do you know if there's some side effect or something that makes the code generation different? I can't think of a reason the compiler wouldn't choose to optimize these the same way, but I also am not very good at knowing what the compiler can optimize intuitively.

0

u/friedkeenan Sep 20 '26 edited Sep 20 '26

Interestingly, GCC seems to optimize the if statement better than the ternary here: https://godbolt.org/z/z3adjxT7o

EDIT: I didn't look closely enough at the assembly, but replacing the ternary with an immediately invoked lambda results in the same assembly

1

u/v4lt5u Sep 20 '26

Isn't the ternary version computing two ints per iteration branchlessly? https://quick-bench.com/q/zlLyGZ8K9bLKnSN0ZkTXh6-iURw

1

u/friedkeenan Sep 20 '26

Oh yeah, you're right, that's my bad. I should've looked closer at the assembly (I saw the larger assembly and a couple extra cmps and went welp there you have it). If one replaces the ternary with an immediately invoked lambda then it results in the same assembly: https://godbolt.org/z/rWMM4rcqr

1

u/kvitterk Sep 19 '26

That is my experience too. Ternary or if statement is only a cosmetic difference.

-6

u/RadimPolasek Sep 19 '26

Have you checked the code in godbolt?

7

u/Total-Box-5169 Sep 19 '26

OP included binary code.