Using the benchmarking method described in my previous post, I set out to discover which is faster: C++ If statements or switch statements.
To do the test I had to ensure that the code was exactly the same besides the If and switch statement portions of the code. Below are my two like functions:
void IfStatement(){
int val = 5;
string value = "";
for(int i = 0; i < 1000000; i++){
if(val == 1) value = "one";
else if(val == 2) value = "two";
else if(val == 3) value = "three";
else if(val == 4) value = "four";
else if(val == 5) value = "five";
else value = "unknown";
}
}
void SwitchStatement(){
int val = 5;
string value = "";
for(int i = 0; i < 1000000; i++){
switch(val)
{
case 1:
value = "one";
break;
case 2:
value = "two";
break;
case 3:
value = "three";
break;
case 4:
value = "four";
break;
case 5:
value = "five";
break;
default:
value = "unknown";
break;
}
}
}
Each function loops a total of 1 million times to make the difference in speed more apparent. The functions are called 100 times each and the average of the speeds is taken into account.

Switch statement seems to execute 7 ms. faster
I’ve ran the test several times and it seems that the switch statement actually executes on average, 7 ms. faster than an If statement (48 ms vs 55 ms), or almost 13% faster. Of course, this wouldn’t even be noticeable in most applications. But if you plan on looping a particular function enough times it would be a good idea to optimize it in any way possible.
Note: It was brought to my attention by a frequent visitor that timings may vary quite a bit. It is my assumption this is due to hardware or even quite possibly, choice of OS. For these tests I am running Vista x64 with 8GB of ram and an Intel Core2Quad @ ~2.67 ghz.
I’ve provided the source code below so you can see for yourself. I’ll be doing more benchmarks in the future with other functions and languages to compare.
Download

Home
Projects
Hosting
Advertising
About
Archive
Contact
Forums
Subscribe
Nice test. Looking forward to seeing some more benchmarks.
Reply