Remix.run Logo
craftkiller 4 hours ago

Here's an example of removing a branch that was posted to HN a little over a month ago: https://www.greyblake.com/blog/branchless-rust/

metabagel 4 hours ago | parent | next [-]

From the article:

=====

Should you go branchless?

Most of the time, no. Branchless code is harder to read and easier to get wrong. Besides, compilers know a lot of tricks and already do a lot of this work for us.

Only when a profiler points at a hot loop, and the loop contains a branch on unpredictable data this technique can pay off big.

metabagel 4 hours ago | parent | prev | next [-]

OK, but the code with the branch is easier to understand.

robby_w_g 4 hours ago | parent | next [-]

Yeah, I don't buy the premise that branchless code is intrinsically easier to understand. Maybe OP's point is that adding unnecessary branches makes code harder to read? But that's generally the case for any unnecessary code.

winternewt 3 hours ago | parent [-]

I see stuff along the lines of:

  if (x == 0) {
      return y;
  }
  
  y += 25*x;
  return y;
and skipping the if just makes the function shorter and simpler, while also not involving the CPU branch prediction. Another one that doesn't necessarily skip all branching but at least drops one - and more importantly makes the code simpler and easy to verify, is removing the if statement in code like

  if (count == 0) {
      return;
  }

  for (int i = 0; i != count; i++) {
    puts("hello");
  }
jamiejquinn 4 hours ago | parent | prev [-]

Generally agree. As with many optimisations, branchless code can easily be less obvious than the branchy equivalent.

cestith 4 hours ago | parent | prev [-]

That's a really nice example. Thanks.