I tried to compare the performance of switch
statement and lookup tables as below.
This is the code using switch
statement
#include <stdio.h>
int main()
{
int n = 3;
for (long i = 0; i < 10000000; ++i) {
switch (n) {
case 0:
printf("Alpha");
break;
case 1:
printf("Beta");
break;
case 2:
printf("Gamma");
break;
case 3:
printf("Delta");
break;
default:
break;
}
}
return 0;
}
And here is the code using lookup tables:
#include <stdio.h>
static char const * const Greek[4] = {
"Alpha",
"Beta",
"Gamma",
"Delta"
};
int main()
{
int n = 3;
for (long i = 0; i < 10000000; ++i) {
if (n >= 0 && n < 4) {
printf(Greek[n]);
}
}
return 0;
}
I run two program on ubuntu 14.04, gcc version 4.8.4, using perf version 4.4.13 to analyze performance. And result:
I don't know why Switch Statement run slower than Lookup tables. As I known, Switch Statement using jump table, i think it should run faster than Lookup tables in my program (it has additional if statement).
If you are compiling with optimizations, your code has no switch and no lookup table. I's just a for loop which calls printf()
many times with the same fixed string. Any minimally reasonable compiler will in fact detect that n = 3
is never changed and optimize it out. Maybe you can add a n = rand() % 4;
just inside the loop.
On the other end if you are not compiling with optimizations, taking timings is meaningless.
Coming to your question, I expect the lookup table to be faster than the switch statement, since the switch statement will totally thrash the Branch Prediction, while the if will be no problem, being always true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With