I have a Solver class that reads data from a System class and calculates a solution for the system current state. Depending on the system data, there are different member functions that I should call to get each value of a huge matrix. My question is: If I use function pointers instead of if statements, will I get better performance? (this procedure is repeated several times and I wish to optimize it)
System
class System
{
friend class Solver;
public:
void print();
//...
private:
double x[n];
int equationType[n];
//...
}
Solver with If statements
class Solver
{
public:
//...
void solve(){
for(int i=0; i<n; ++i){
if(sys->equationType[i] == 1)
solveForEq1(i, x[i]);
else if(sys->equationType[i] == 2)
solveForEq2(i, x[i]);
else if //...
}
private:
System *sys;
void solveForEq1(int, double);
void solveForEq2(int, double);
//...
}
Solver with function pointers (will this actually work? and faster?)
typedef void (Solver::*MemFuncPtr)(int, double);
class Solver
{
public:
//...
Solver(System* s) : sys(s){
mfp[0] = &Solver::solveForEq1;
mfp[1] = &Solver::solveForEq2;
}
void solve(){
for(int i=0; i<n; ++i)
*(mfp[equationType[i]])(i, x[i]);
}
private:
System *sys;
MemFuncPtr mfp[2];
void solveForEq1(int, double);
void solveForEq2(int, double);
//...
}
It will work faster without the if statement.
If statements make your CPU chace 80% of the positive branch, which leads to cache misses when going for negative branches.
Whenever you are able to get rid of a "if" statement then you made a huge improvement.
Considering your case where you don't have the positive branch the usual case scenario (usual case scenario for a positive branch is something like if (argument!=NULL) ), then you should have a significant performance gain.
The performance gain also varies accourding to CPU type (RISC or CISC).