DEV Community

pmgzo
pmgzo

Posted on

Branchless programming

Hi folks, I hope you're doing well.
Today I wanted to talk about Branchless programming.
Basically at a binary level, the compiler builds branches according to instructions.

What creates those branches are the if, else, else if statements. Otherwise any conditional instructions that create those branches.

A simple example (of C code) of that is:

int x = 5;

if (x > 10) {
  // do stuff
}
else {
  // do something else
}
Enter fullscreen mode Exit fullscreen mode

Basically in this example your processor will put the instruction set in their cache memory when arriving to this instruction.

If the condition is not valid, it will unload the instructions within the if block and load those in else block

Which cost time computation because of the load and unload process.

Maybe, the compiler/processor have changed but at least this is what I learned about Branchless programming

Branchless programming is a way to code your program to avoid branches. Basically it's a way to trick the compiler to avoid additional instruction. Basically it is said that's better to do ternary return statement instead of the previous approach:

int your_condition(int x) {

  return x > 10 ? call_function1(x) : call_function2(x);
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading, and see you in the next one 👊

Top comments (0)