I was benchmarking function pointers vs switch case statements in quick-bench and got the expected result. Function pointers are slower than switch case. But I wanted to remove the operation from the equation and get just the cost of the control flow. Thats when I tried a third implementation thats just a foor loop with an array index. To my suprise it was the slowest of all of them. How can the simplest option that has all the information easily avaible be the slowest?
Settings on quick-bench: (Clang 16.0, C++20, O3) quick-bench result
Snippet SwitchCase:
unsigned state1(unsigned *state, unsigned *counter, unsigned var)
{
if(0 == (var % 89))
{
*state = 2;
*counter += 1;
return var;
}
return var -1;
}
...
unsigned int myInt = numberOfTries;
unsigned int state = 1;
unsigned int counter = 0;
while (0 != myInt)
{
switch (state)
{
case 1:
myInt = state1(&state, &counter, myInt);
break;
...
case 10:
myInt = state10(&state, &counter, myInt);
break;
}
}
Snippet ForLoopMod:
unsigned int myArr[] = { 89, 83, 79, 73, 71, 67, 61, 59, 53, 47 };
unsigned int myArrIndex = 0;
unsigned int myInt = numberOfTries;
unsigned int counter = 0;
while (0 != myInt)
{
if (0 == (myInt % myArr[myArrIndex]))
{
counter++;
myArrIndex++;
myArrIndex %= 10;
}
else
{
myInt--;
}
}