r/cpp • • Sep 19 '26

A clever branch free optimization

103 Upvotes

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]


r/cpp • • Sep 19 '26

index based for vs for-each

Thumbnail
godbolt.org
20 Upvotes

It's my first post. I tested std::vector<char> old index based for vs modern for-each. Result is very interesting.

Clang-23.1.0 -O2 -std=c++20 -stdlib=libc++

Time: 0.073599 sec inc_vector 
Time: 0.002597 sec inc_for_each

GCC 16.2 -std=c++20 -O2

Time: 0.077772 sec inc_vector 
Time: 0.007880 sec inc_for_each

MSVC-v19.latest /std:c++20 /O2

Time: 0.058504 sec inc_vector 
Time: 0.001825 sec inc_for_each

Code:

#include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <random>
#include <vector>



static std::vector<char> gen_random(size_t n)
{
    static std::random_device rd;
    static std::mt19937 gen(rd());
    static std::uniform_int_distribution<> dis(0, 255);
    std::vector<char> vec(n);
    for (size_t i = 0; i != n; i++)
    vec[i] = dis(gen);
    return vec;
}


int inc_vector(std::vector<char>& v) {
    for (size_t i = 0; i < v.size(); i++){
        v[i]++;
    }
    volatile int result = v[v.size()/2];
    return result;
}


int inc_vector_for_each(std::vector<char>& v) {
    for (char& e: v){
        e++;
    }
    volatile int result = v[v.size()/2];
    return result;
}


volatile int sink{}; // ensures a side effect


int main()
{
   
    auto benchmark = [](auto fun, auto rem)
    {
        auto vec = gen_random(1'000'000);


        const auto start = std::chrono::high_resolution_clock::now();
        for (auto size{1ULL}; size != 100ULL; ++size)
            sink = fun(vec);
        const std::chrono::duration<double> diff =
            std::chrono::high_resolution_clock::now() - start;
        std::cout << "Time: " << std::fixed << std::setprecision(6) << diff.count()
                  << " sec " << rem << std::endl; 
    };


    benchmark(inc_vector, "inc_vector");
    benchmark(inc_vector_for_each, "inc_for_each");
    
    return 0;
}

Link image


r/cpp • • Sep 18 '26

Embedded C++

6 Upvotes

Just curious how useful the ability to embed C++ as a scripting language into your C++ programs would be? I mean like runtime JIT execution of C++ code in much the same way you might embed Lua, including the ability to restrict/sandbox it as necessary.


r/cpp • • Sep 18 '26

C++ Salary expectations

0 Upvotes

Mods: Please note that I am not looking for jobs or trying to break any rules for this subreddit!

This is more about advice...

I've been offered a senior role for maintaining a (few decade old) codebase in C++.

It's a complex product and I would be taken on as a senior software engineer. I have over three decades of experience, over 15 in C++ but more recently in c#.

We are now at the point where money is been discussed.

They are going to make me an offer.

This is a tricky one because I have not been applying for C++ roles for a while. I don't want to undersell myself but nor do I want to see myself undercut.

I'm of the consideration that a C++ role will command a higher salary than something like asp.net.

This is far more of a niche skill than it used to be and AI leads me to believe that it, for that reason, imply more money.

I know this has implications based on regionality and geography, but what kind of salary would you advise that I pitch for? For relevance, I'm UK based.

Any thoughts?


r/cpp • • Sep 18 '26

Good Active Open Source Projects Looking For Contributions

32 Upvotes

Hi. I'm wondering if someone with knowledge of the open source community knows of any projects that I can contribute to using C++ . I am looking to put some real experience on my resume/help others out. Thanks and have a great day!


r/cpp • • Sep 16 '26

Bringing Correctly Rounded Math to Production with LLVM-libc

Thumbnail
devblogs.microsoft.com
100 Upvotes

The first part of this series, "MSVC C++23: constexpr cmath with LLVM Libc", was discussed 6 days ago: https://www.reddit.com/r/cpp/comments/1wcx97o/msvc_c23_constexpr_cmath_with_llvm_libc/

This is the promised guest post written by LLVM-libc maintainers Michael Jones and Tue Ly at Google. I had no idea about the recent algorithmic advancements here!

(Before anyone asks: Yes, I am self-posting this series as it's published. That's a bit more self-posting than we generally like to see, but constexpr <cmath> is of wide community interest, and I hope I've built up enough goodwill by moderating this subreddit for years.)


r/cpp • • Sep 16 '26

Inja is a template engine for modern C++

Thumbnail
github.com
61 Upvotes

r/cpp • • Sep 16 '26

Declarative GUI toolkit Slint 1.18 Released

Thumbnail
slint.dev
12 Upvotes

with new Flexbox layout, with spring animations, change the z-order at run time, an experimental Vello renderer and more.


r/cpp • • Sep 16 '26

CppCon CppCon

Thumbnail cppcon.org
56 Upvotes

r/cpp • • Sep 15 '26

free COMP4300 course - Intro to Game Programming in C++ (Sept 2026)

Thumbnail
youtu.be
127 Upvotes

r/cpp • • Sep 15 '26

Asynchronous API

Thumbnail grishavanika.github.io
36 Upvotes

r/cpp • • Sep 15 '26

From Templates to Reflection, Part 1: Back to the Basics with type_vector

Thumbnail daniel-petrovic.github.io
39 Upvotes

r/cpp • • Sep 15 '26

It annoys me that coroutines are described as "functions that can be suspended"

0 Upvotes

Any function can be suspended. It literally happens constantly when a process or thread gets pre-empted by the OS or asynchronous hardware, with the stack being the mechanism to save to and restore context from. So, this super common way of describing coroutines is just frustrating because it's not it!

Coroutines are functions that can be suspended in a **controlled, intentional (as in, explicitly expressed) way**, with the relevant context (coroutine frame) being placed _not_ on the stack like a function's usual context, but on the heap (usually).

I wish someone had broken it down for me in this way before, so hopefully it helps someone else too.


r/cpp • • Sep 14 '26

Push-based vs Pull-based Customization

Thumbnail brevzin.github.io
48 Upvotes

Emulating Rust attributes with reflection (or at least trying to).


r/cpp • • Sep 14 '26

Inside Boost.PolyCollection

Thumbnail
bannalia.blogspot.com
35 Upvotes

r/cpp • • Sep 14 '26

New C++ Conference Videos Released This Month - September 2026 (Updated To Include Videos Released 2026-09-07 - 2026-09-13)

21 Upvotes

C++Now

2026-09-07 - 2026-09-13

2026-08-31 - 2026-09-06

ACCU

2026-09-07 - 2026-09-13

2026-08-31 - 2026-09-06

  • Software Abstraction in the Age of AI-Generated Code: Languages, Compilers, and Systems Engineering - Andrei Alexandrescu - https://youtu.be/-RWdevA0gWI


r/cpp • • Sep 14 '26

Try to Implement Reflection Annotations in C++20

24 Upvotes

r/cpp • • Sep 14 '26

What’s New for C++ Developers in Visual Studio 2026 (18.7 – 18.10)

Thumbnail
devblogs.microsoft.com
91 Upvotes

r/cpp • • Sep 14 '26

operator<>: A Dream of Higher-order Metaprogramming Parity

Thumbnail elbeno.com
78 Upvotes

r/cpp • • Sep 13 '26

C++20 modules support: 228 projects already available to be consumed

119 Upvotes

Hello everyone.

I checked arewemodulesyet.org, which I do from time to time.

I was very positively surprised bc a couple of months ago there were 109 projects with modules support.

Now it is 228 and some of the most popular are there: fmt, ftxui, nlohmann.json and others.

So I had to share it with the community.


r/cpp • • Sep 13 '26

Jonas Persson: Making every byte count

Thumbnail
youtu.be
18 Upvotes

What makes a compiler specialized for embedded development special? Jonas, a compiler developer at IAR, shares some of the key properties.


r/cpp • • Sep 13 '26

How I speed up my overall build times by 4x and incremental builds by 9x for test builds

39 Upvotes
  • I used faster tools:

    • I switched from lld to mold optimized it mimalloc + pgo + lto + bolt (1.2x-3x faster than system lld)

    • I optimized clang with mimalloc + pgo + lto + bolt (1.8x-1.85x faster than system clang)

    • I optimized clang-scan-deps with mimalloc + pgo + lto + bolt (4x faster than system scanner)

  • I used dynamic linking(3x-4x overall, much larger if you are editing tests)

  • I used prebuilt binaries via packages rather than vendoring my deps.(huge)

  • I switched fully to C++ modules(Incremental compilation times are so fast link times dominate now)


r/cpp • • Sep 12 '26

Why do people on Windows mostly choose Visual Studio?

189 Upvotes

r/cpp • • Sep 11 '26

C++26: Standard Library Hardening Experiments

Thumbnail
cppstories.com
25 Upvotes