Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ most efficient if statement evaluation

X is true nearly 99.9% of the time but I need to handle Y and Z as well. Although the body of the X condition is empty, I'm thinking it should be faster than potentially checking 2 other conditions Y and Z if the X condition is omitted. What do you think?

if (likely(X))
{
}
else if (unlikely(Y))
{
...
}
else if (unlikely(Z))
{
...
}
like image 964
chriskirk Avatar asked Jan 19 '12 21:01

chriskirk


People also ask

Are IF statements efficient?

Efficient if-else Statements While in a serial if block, all the conditions are tested, in an if-else block the remaining tests are skipped altogether once an if expression evaluates to true. This approach is known as a circuit-breaker behavior and is way more efficient than a serial if block.

Is an if statement expensive?

The if statement is the most expensive [something]. [something] registers [something].

DO IF statements slow down code?

Nope. In fact, it'll actually speed it up in most cases (because it's allowed to skip over blocks of code). If you're considering merging a bunch of if statements into one: don't, you won't get any benefits.


3 Answers

You might want to know what exactly happens when you use likely or unlikely:
http://kerneltrap.org/node/4705

I would personally write

if (unlikely(!X))
{
  if (unlikely(Y))
  {
  ...
  }
  else if (unlikely(Z))
  {
   ...
  }
}

Which means if x, continue execution, else jump to if body.

like image 157
log0 Avatar answered Oct 15 '22 12:10

log0


As usual, when in doubt profile; anyhow, if I were to read that code I would find much clearer something like:

if (!likely(X))
{
    if (unlikely(Y))
    {
    ...
    }
    else if (unlikely(Z))
    {
    ...
    }
}
like image 24
Matteo Italia Avatar answered Oct 15 '22 12:10

Matteo Italia


If a compiler is to assume, it would generally favor the first condition true.

you can use something like __builtin_expect to control this (as Ugo detailed).

If it's in a loop, you should measure because hardware is also a consideration -- it's not just the source and the compiler. How's your cache, and how's branch prediction working for you? Profile. Alter. Profile. Compare.

like image 30
justin Avatar answered Oct 15 '22 11:10

justin