I’m deciding whether to use if/else vs switch/case in a PHP site that I am writing and I was wondering if there were any benefits to using one or the other or if there were certain instances where one was intended to be used rather than the other.
I’m deciding whether to use if / else vs switch / case in a
Share
Interesting question because in a compiled languaged (or JIT’ed language even) there is a nice performance gain when using switch statements because the compiler can build jump tables and will run in constant time. Even switching on a string can be optimized as the string can be hashed. However, from what I’ve read, it appears php makes no such optimization (I’m assuming because it’s interpreted and runs line by line).
Great .Net article about switch optimization: If vs. Switch Speed
Regarding php being interpreted, the PHP docs says: http://php.net/manual/en/control-structures.switch.php
I also found several references all suggesting that if / else statements in php may actually be faster than switch statements (weird). This probably is not true if you compile php (something I’ve never done, but apparently it’s possible).
http://www.fluffycat.com/PHP-Design-Patterns/PHP-Performance-Tuning-if-VS-switch/
This article in particular, http://php100.wordpress.com/2009/06/26/php-performance-google/, is interesting as the author compares internal php code of if vs switch and they are nearly identical.
Anyways, I would say that any performance gain will be insignificant one way or the other, so it’s more of a user preference. If statements are more flexible and you can more easily capture ranges of values (especially large ranges) as well as do more complex comparisons whereas switch statements line up to exactly one value.