So, there's this rule to try to pull if
statements out of high repetition loops:
for( int i = 0 ; i < 10000 ; i++ )
{
if( someModeSettingOn ) doThis( data[i] ) ;
else doThat( data[i] ) ;
}
They say, it's better to break it up, to put the if statement outside:
if( someModeSettingOn )
for( int i = 0 ; i < 10000 ; i++ )
doThis( data[i] ) ;
else
for( int i = 0 ; i < 10000 ; i++ )
doThat( data[i] ) ;
(In case you're saying "Ho! Don't optimize that yourself! The compiler will do it!") Sure the optimizer might do this for you. But in Typical C++ Bullshit (which I don't agree with all his points, eg his attitude towards virtual functions) Mike Acton says "Why make the compiler guess at something you know? Pretty much best point of those stickies, for me.
So why not use a function pointer instead?
FunctionPointer *fp ;
if( someModeSettingOn ) fp = func1 ;
else fp = func2 ;
for( int i = 0 ; i < 10000 ; i++ )
{
fp( data[i] ) ;
}
Is there some kind of hidden overhead to function pointers? Is it is efficient as calling a straight function?
In C, we can use function pointers to avoid code redundancy. For example a simple qsort() function can be used to sort arrays in ascending order or descending or by any other order in case of array of structures. Not only this, with function pointers and void pointers, it is possible to use qsort for any data type.
Traditionally, function-pointer tables were faster than switch. Nowadays it shouldn't matter. In fact function pointers might slow things down a tiny bit since they block inlining.
Function pointers in C can be used to create function calls to which they point. This allows programmers to pass them to functions as arguments. Such functions passed as an argument to other functions are also called callback functions.
In this example it's impossible to say which case will be faster. You need to profile this code on target platform/compiler to estimate it.
And in general, in 99% case such code need not to be optimized. It's example of evil premature optimization. Write human-readable code and optimize it only if need after profiling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With