Trying to optimize the fun_a1()
function. The variable j
does not change in the scope of fun_a1()
. So, checking j==1 or 2 or 3 for each 'i' iteration is obviously a waste of CPU cycles. But if I try to bring the condition evaluation outside the loop, I have to write redundant loops for each condition. In C, I can solve this easily by using a function pointer. However, C++ will not allow pointers to non-static functions. I found a few links describing the mysterious "pointer-to-member". (example 1, example 2) But it's still not clear how do I use it from inside the object itself e.g from inside fun_a()? Or can it be optimized in any other ways?
class A{
void fun_b(int i);
void fun_c(int i);
void fun_d(int i);
void fun_f(int i);
void fun_a1(int j){
for(int i=0; i<1000; i++){
if(j==1) fun_b(i);
else if(j==2) fun_c(i);
else if(j==3) fun_d(i);
fun_f(i);
}
}
void fun_a2(int j){
if(j==1){
for(int i=0; i<1000; i++) {
fun_b(i);
fun_f(i);
}
}
else if(j==2){
for(int i=0; i<1000; i++) {
fun_c(i);
fun_f(i);
}
}
else if(j==3){
for(int i=0; i<1000; i++) {
fun_d(i);
fun_f(i);
}
}
}
};