Tuesday, 10 August 2010

Hidden Branches

How often do we use if's and function calls without thinking about the cost? Quite often I'd bet. But in addition to the branch operations that are explicit, there are some that are hidden, or implicit. Consider the humble logical and operation &&

if( A==1 && B==2 && C==3 )
{
// I needed to branch three times to get here
}
else
{
// I needed to branch at least once to get here, possibly two times, sometimes three.
}

consider the alternative

resultA = A-1;
resultB = B-2;
resultC = C-3;

if( !( resultA|resultB|resultC ) )
{
// I needed to branch once to get here
}
else
{
// I needed to branch once to get here
}

This is better because it's more consistent, there is no short-circuiting going on. Short circuits worked well when CPU time mattered. Now it doesn't so much. It only matters when the arguments in the short circuit depend on previous items in the chain:

if( pThing && pThing->GetStuff() && pThing->GetStuff()->IsOkay() )
{
//...
}

But this coding style is slow and should be used sparingly.
Post a Comment