- What is faster: Function pointers or switch?
The switch statement would have around 30 cases, consisting of enumarated unsigned ints from 0 to 30.
I could do the following:
class myType
{
FunctionEnum func;
string argv[123];
int someOtherValue;
};
// In another file:
myType current;
// Iterate through a vector containing lots of myTypes
// ... for ( i=0; i < myVecSize; i ++ )
switch ( current.func )
{
case 1:
//...
break;
// ........
case 30:
// blah
break;
}
And go trough the switch with func every time. The good thing about switch would also be that my code is more organized than with 30 functions.
Or I could do that (not so sure with that):
class myType
{
myReturnType (*func)(int all, int of, int my, int args );
string argv[123];
int someOtherValue;
};
I’d have 30 different functions then, at the beginning a pointer to one of them is assigned to myType.
- What is probably faster: Switch statement or function pointer?
Calls per second: Around 10 million.
I can’t just test it out – that would require me to rewrite the whole thing. Currently using switch.
I’m building an interpreter which I want to be faster than Python & Ruby – every clock cycle matters!
Switch statements are typically implemented with a jump table. I think the assembly can go down to a single instruction, which would make it pretty fast.
The only way to be sure is to try it both ways. If you can’t modify your existing code, why not just make a test app and try it there?