Search code examples
optimizationcompiler-constructionembeddedbranchbranch-prediction

branch prediction, and optimized code


I have following set of code blocks, the purpose of the both block is same. I had to implement the 2nd block to avoid inverse logic and to increase the readability. BTW, in the production code the condition is very complex.

The question is - I know branching is bad, how much penalty I have to pay. Just as an extra info, please also consider, the probability of else branch is very high.

X = Get_XValue()
if (X != 5)
{
    K = X+3;
    .
    .
}

X = Get_XValue()
if (X == 5)
{
    /*do nothing*/
}
else
{
    K = X+3;
    .
    .
}

Solution

  • This all comes down to your compiler. A good optimizing compiler will detect that the then-clause in the second example is empty and reverse the test. Thus it will generate the same code for both cases so there should be no penalty at all.

    As a side note, I can add that this was the case for all three compilers I tried (clang, gcc, and iccarm),