php - PHP 中的 Switch-Case 和 If-Else 有什么区别?

标签 php

我正在决定是否在 PHP 站点中使用 if/elseswitch/case我正在写作,我想知道使用其中一种是否有任何好处,或者在某些情况下是否打算使用一种而不是另一种。

最佳答案

这个问题很有趣,因为在编译语言(甚至是 JIT 语言)中,使用 switch 语句会带来很好的性能提升,因为编译器可以构建跳转表,并且会在恒定时间内运行。甚至可以优化字符串的开关,因为可以对字符串进行哈希处理。但是,根据我的阅读,php 似乎没有进行此类优化(我假设是因为它是逐行解释和运行的)。

关于开关优化的很棒的 .Net 文章:If vs. Switch Speed

关于解释 php,PHP 文档说: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.

我还发现一些引用文献都暗示 php 中的 if/else 语句实际上可能比 switch 语句更快(很奇怪)。如果你编译 php,这可能不是真的(我从未做过,但显然这是可能的)。

http://www.fluffycat.com/PHP-Design-Patterns/PHP-Performance-Tuning-if-VS-switch/

特别是这篇文章,http://php100.wordpress.com/2009/06/26/php-performance-google/ , 很有趣,因为作者比较了 if 与 switch 的内部 php 代码,它们几乎相同。

无论如何,我会说任何性能提升都是微不足道的,所以它更像是一种用户偏好。 If 语句更灵活,您可以更轻松地捕获值的范围(尤其是大范围)以及进行更复杂的比较,而 switch 语句恰好与一个值对齐。

关于php - PHP 中的 Switch-Case 和 If-Else 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7290889/

相关文章:

php - 在类别页面中显示最低的简单产品价格

php - 在 PHP 中验证输入后将表单数据重定向/发布到站点

php - LAMP 站点上较长的目录路径/名称和 URL 有哪些缺点?

php - CodeIgniter Controller ,如何避免重复代码?

php - mysql 日期显示 30/11/-000 而不是 0000-00-00

php - 数据库设计 : User with access to specific pages

php - 为什么这容易发生 SQL 注入(inject)?

php - mysql数据库按列搜索

php 查询函数/类

php - 如何在服务器端访问 PHP REST API PUT 数据?