Please consider branch prediction before answering this question.
I have several scenarios where I can replace a conditional statement with a function call using a function pointer. Some things 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)
IF you are considering the above cases, both achieve the same results. But I am thinking about increasing productivity. In the second case, I avoid the problem of predicting branching by calling a function.
Now let me know what is the best practice and “best optimized code” in such senarii. (By the way, I don’t like the statement “Pre-mature optimization is the root of all evil”, since optimization has advantages, so I think I need to optimize my code!)
PS: I don’t mind if someone gives a detailed overview of "how poor branch prediction can be" even in the assembly code.
Update: after profiling (similar code above),
If the condition is met in this form senario.Can anyone gives a reason for this? Functional calling code can be programmed, since there is no branch code? But here its appearance looks different: the winning code wins !: O Profiling on optimization Intel Mac Osx, GCC O3 / Os. A.
c ++ optimization compiler-optimization architecture data-oriented-design
Ayyappa
source share