Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

What is the difference between Switch-Case and If-Else in PHP?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...