Using function pointers, if the compiler doesn't remove them, is a serious performance hit.
A raw if on an unchanged local variable will be probably optimized out of the loop: that isn't a very fancy optimization.
However, if you want to make this explicit, the answer isn't function or method pointers. It is lambdas and functors.
template<typename Functor>
void fun_a2_internal(Functor f) {
for(int i = 0; i < 1000; ++i) {
f(i);
}
}
void fun_a2(int j) {
if (j==1)
fun_a2_internal([&](int i){ fun_b(i); fun_f(i); });
else if (j==2)
fun_a2_internal([&](int i){ fun_c(i); fun_f(i); });
else if (j==3)
fun_a2_internal([&](int i){ fun_d(i); fun_f(i); });
}
here we write a fun_a2_internal
whose job it is to do a loop, and do some task in the loop.
Our fun_a2
passes that task in as a functor via a lambda.
This has the effect that the compiler gets to know the details of the body of the loop when compiling the loop, because the functor's operator()
is a non-virtual one, and thus the same for every instance.
In general, if your answer to an optimization problem is "use function pointers" (or member pointers), you have the wrong answer.
This technique is why C++'s std::sort
is faster than C's qsort
.