To investigate whether case statements are faster than an "if-else ladder", I wrote a script to generate C code. Here's an example of the generated code:
Code:
#include <sys/time.h>
int if_else_proc(int);
int switch_proc(int);
float time_diff(struct timeval, struct timeval);
int main()
{
int n, i;
struct timeval start, end;
srandom(time(0));
gettimeofday(&start, 0);
for(i = 0; i < 10000; i++)
{
n = random() % 6;
if_else_proc(n);
}
gettimeofday(&end, 0);
printf("Milliseconds processing if elses: %f\n", time_diff(start, end));
gettimeofday(&start, 0);
for(i = 0; i < 10000; i++)
{
n = random() % 6;
switch_proc(n);
}
gettimeofday(&end, 0);
printf("Milliseconds processing cases: %f\n", time_diff(start, end));
return 0;
}
float time_diff(struct timeval start, struct timeval end)
{
if (start.tv_usec > end.tv_usec)
{
end.tv_usec += 1000000;
end.tv_sec--;
}
return (end.tv_sec - start.tv_sec)*1000 +
(end.tv_usec - start.tv_usec)/1000.0;
}
int if_else_proc(int n)
{
if(n == 0) {return n;}
else if(n == 1) {return n;}
else if(n == 2) {return n;}
else if(n == 3) {return n;}
else if(n == 4) {return n;}
else {return -1;}
}
int switch_proc(int n)
{
switch(n)
{
case 0: return n;break;
case 1: return n;break;
case 2: return n;break;
case 3: return n;break;
case 4: return n;break;
default: return -1;break;
}
}
When the mod value stayed the same whether there were 100, 1000, or 10000 if-else/switch statements, the switch statement would be about half a millisecond faster than the if-else statements, but all would take the same amount of time regardless of the number of cases. However, when the mod value was equal to the number of cases plus 1, I saw that the switch statement outperfomed the if-else statements. Here's a table of my results in milliseconds:
Code:
cases if-else switch
100 2.892 2.003
500 11.169 2.02
1000 67.03 2.06
This shows that the compiler, which in my case is GCC, uses some kind of indexing scheme for switch statements. I'll have a look at the assembly later.
[edit]I'd like to add that the above output does not reflect any optimizations. With -O2, the if-else processes faster, but the switch is still much faster than the if-else.[/edit]