Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ optimization if performance

consider these 2 situations of if statements:

if( error ==0 )
{
    // DO success stuff
}
else
{
    // DO error handling stuff
}

and this one:

if( error != 0 )
{
    // DO error handling stuff
}
else
{
    // DO success stuff
}

which one over performs the other, knowing that most of the time I come to the success code path.

like image 381
mmohab Avatar asked Sep 06 '25 03:09

mmohab


1 Answers

Rather than worrying about this which might be a performance issue only in the rarest of cases, you should ask yourself which is more readable. For error checks, you could use a guard clause, which avoids too many indentations/brackets:

if( error != 0 )
{
    // DO error handling stuff
    return;
}

// DO success stuff

If you know that one path is more likely than the other and you are sure that this is really performance critical, you could let the compiler know (example for GCC):

if( _builtin_expect (error == 0, 1) )
{
    // DO success stuff
}
else
{
    // DO error handling stuff
}

Of course, this makes the code harder to read - only use it if really necessary.

like image 86
mrks Avatar answered Sep 08 '25 00:09

mrks