When implimenting a state machine in c++ code it could be implimented using a Function Prototypes, Case /Switch statements, or If / Else if structures. What is faster though?
I ran a couple of tests on Visual studio 2005.

Function Prototypes are always slower than case statements.
If statements are only fastest when less than6 states are used.
Here is the quick and dirty code for testing.
Speed test code file
Sam Uncategorized
#include “stdafx.h”
#include <iostream>
#include <iomanip>
using namespace std;
class test{
public:
void hi(){
static int i=0;
cout << i++<<endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
test A;
test B;
A.hi(); //prints 0
A.hi();// prints 1
B.hi();// prints 2
int x;
cin >>x;
return 0;
}
Sam Uncategorized
#include <iostream>
#include <iomanip>
using namespace std;
void Add(int x,int y);
void Sub(int x,int y);
void (* fun)(int x,int y);
int _tmain(int argc, _TCHAR* argv[])
{
int x;
cout <<”Test\n”;
fun = Add;
fun(1,2);
fun = Sub;
fun(1,2);
cin >> x;
return 0;
}
void Add(int x,int y){
cout << x+y<<endl;
}
void Sub(int x,int y){
cout << x-y<<endl;
}
Sam Uncategorized