Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is cutting if statements by using function pointers going to be more efficient?

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?

like image 290
bobobobo Avatar asked Jun 19 '12 14:06

bobobobo


People also ask

What is the advantage of using function pointers?

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.

How is function pointer advantageous vs switch case?

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.

Why do we use function pointers in C?

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.


1 Answers

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.

like image 67
inkooboo Avatar answered Nov 16 '22 00:11

inkooboo