Switch vs. If January 27, 2008
Often, with little rhyme or reason behind it, I choose between using a switch condition or an if-else statement while coding simple condition matches in PHP. I got curious about which is actually more efficient at matching a random integer with a set of conditionals. So, I setup a script to create a set of large scripts to test the speed of these different constructs. Using the ‘time’ command, I measured the speed at which the condition could match a random number. Here is what I found:
The switch construct is generally more than twice as fast at matching a simple integer within a single large set of conditions.
There is largely little difference between the time it takes to find a condition using if,if statements or if-elseif statements. Also the size of the resulting scripts were only negligibly different compared to the difference in execution time.
At first I thought that since the switch statement breaks execution after it matches its value especially since I was using random numbers, that this could account for the time difference, but that also had no bearing. Setting $var=999999 in the below statements had little effect on the faster execution time of the switch statement.
If-Elseif
<? $var=rand(0,1000000); if ($var==0) { echo "found 0"; } elseif ($var==1) { echo "found 1"; } elseif ($var==2) { echo "found 2"; } .... ?>
If,If
<? $var=rand(0,1000000); if ($var==1) { echo "found 1"; } if ($var==2) { echo "found 2"; } if ($var==3) { echo "found 3"; } .... ?>
Switch
<? $var=rand(0,1000000); switch ($var) { case 1: echo "found 1"; break; case 2: echo "found 2"; break; case 3: echo "found 3"; break; .... ?>
Also, I wondered if the switch condition would overall be less efficient if there were a large number of switch statements within a script, instead of a single switch construct with many cases. The thinking was that the switch condition was possibly more expensive to setup than an if-else. However, in this case, many switch statements still performed faster (around 25% more) than when using many if-else or if,if conditionals instead. This was tested with 100,000 iterations of 10 conditions as opposed to a 1 iteration of 1,000,000 conditions.
Of course, the if else construct is a bit more powerful for more complex condition testing, but if you only have a simple variable to match up against a known set of values, I guess the winner is the switch condition!
Leave a Reply