Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it worth it to rewrite an if statement to avoid branching?

Recently I realized I have been doing too much branching without caring the negative impact on performance it had, therefore I have made up my mind to attempt to learn all about not branching. And here is a more extreme case, in attempt to make the code to have as little branch as possible.

Hence for the code

if(expression) 
  A = C;       //A and C have to be the same type here obviously

expression can be A == B, or Q<=B, it could be anything that resolve to true or false, or i would like to think of it in term of the result being 1 or 0 here

I have come up with this non branching version

A += (expression)*(C-A);   //Edited with thanks

So my question would be, is this a good solution that maximize efficiency? If yes why and if not why?

like image 749
ChangYou Wong Avatar asked Nov 22 '25 15:11

ChangYou Wong


2 Answers

Depends on the compiler, instruction set, optimizer, etc. When you use a boolean expression as an int value, e.g., (A == B) * C, the compiler has to do the compare, and the set some register to 0 or 1 based on the result. Some instruction sets might not have any way to do that other than branching. Generally speaking, it's better to write simple, straightforward code and let the optimizer figure it out, or find a different algorithm that branches less.

like image 183
Lee Daniel Crocker Avatar answered Nov 24 '25 06:11

Lee Daniel Crocker


Jeez, no, don't do that!

Anyone who "penalize[s] [you] a lot for branching" would hopefully send you packing for using something that awful.

How is it awful, let me count the ways:

  1. There's no guarantee you can multiply a quantity (e.g., C) by a boolean value (e.g., (A==B) yields true or false). Some languages will, some won't.
  2. Anyone casually reading it is going observe a calculation, not an assignment statement.
  3. You're replacing a comparison, and a conditional branch with two comparisons, two multiplications, a subtraction, and an addition. Seriously non-optimal.
  4. It only works for integral numeric quantities. Try this with a wide variety of floating point numbers, or with an object, and if you're really lucky it will be rejected by the compiler/interpreter/whatever.
like image 20
Ross Patterson Avatar answered Nov 24 '25 06:11

Ross Patterson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!