Which one is faster ? Function call or Conditional if Statement?

Ayyappa picture Ayyappa · Oct 1, 2011 · Viewed 7.9k times · Source

Please consider the branch prediction too before answering this question.

I have some scenarios where i can replace a conditional statement with a call to a function with the help of function pointer.Some thing like this. (you can think of component based programming over inheritance for a similar type of senario)

     class Shape
     {
        float Area()
        {
            if(type == SQUARE)
             {
                return length*length;
             }
            else if(type == RECTANGLE)
            {
             return length*breadth;
            }
        } 
     }

The same class can be written like this.

       class Shape
     {
        void SetAreaFunction(void *funcptr)//this function is used to set the current AreaFunc
        {
             CurrentAreaFunc = funcptr ;//this holds the pointer to current area func
        }
        float SqauareArea();//this will return square area
        float RectangleArea();//this will return rectangle area 
        float Area()
        {
            currentAreaFunc();
        } 
     }

IF you consider the above cases, both achieves same results.But, I'm thinking about the performance overhead.In the second case I'm avoiding having branch prediction problem by having a function call.

Now let me know which is the better practice and 'better optimized code' in this kind of senarios.(btw, I don't like the statement "Pre-mature optimization is root of all evil" as, optimization has its benefits so i do consider optimizing my code!)

P.S: I don't mind if any one give a detailed overview about 'how bad branch prediction can be" even in assembly code.

Update: After profiling (similar kind of above code),
If Condition succeeded in this kind of senario.Can any one give a reason for this? Functional call code can be prefetched as there is no Branching code right? But here its looks the other way..branching code wins! :O Profiled on Intel Mac Osx,GCC O3/Os optimisation.

Answer

Lior Kogan picture Lior Kogan · Oct 1, 2011

You replaced an if statement with an indirection.

Both your if statement, and the indirection requires memory access.

However, the if will result in a short jump - which will probably won't invalidate the pipeline, while the indirection may invalidate the pipeline.

On the other hand, the indirection is a jump, while the if statement is a conditional jump. The branch predictor may miss.

It is hard to tell which is faster without testing it. I predict that the if statement will win.

Please share your results!