Search code examples
c++cgccif-statementbranch-prediction

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))
{
...
}

Solution

  • 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.