NYCPHP Meetup

NYPHP.org

[nycphp-talk] Switch-Case v. if/else

David Krings ramons at gmx.net
Thu May 14 21:23:44 EDT 2009


Donald J. Organ IV wrote:
> If I remember correctly, if/else if/else statements are faster than 
> Switch-Case.

I heard that the other way around, but that doesn't mean anything. I googled 
switch versus if else and looked at various speed tests that people did. I 
found a few articles discussing PHP specifically, such as this one: 
http://rob.sun3.org/php-code/switch-vs-if/
There it states: "The switch construct is generally more than twice as fast at 
matching a simple integer within a single large set of conditions."
In the end I think it matters only when that part of code gets hit many times 
so that half a second difference in execution really starts to hurt badly.

Contrary to that is the opinion demonstrated on this page: 
http://www.php.lt/benchmark/phpbench.php
Maybe the difference doesn't come out enough with only 1,000 iterations.

> I would suggest converting them and see if you get a performance increase.

Depending on how many switch cases there are that may be quite some effort. 
Switch takes the condition and tests against each case until it finds a match 
or gets to the end of the entire switch block. So if it has to go through many 
cases I could think of two less invasive changes:
- rearrange the order of the cases so that the most likely ones are at the top
- split the switch into multiple switches, but that depends on being able to 
organize the cases into groups

One other thought that comes to mind is that maybe not the switch statement 
itself is slow, but the code that gets executed once a case match is found. 
The comparison on the benchmark page mentioned above makes me believe that 
this might be an option.
Others already hinted to using a profiler, which is likely to be the quickest 
way to find the real bottleneck. What all pages I looked at suggested was 
using === instead of == for the comparison.

David



More information about the talk mailing list