quot;ifquot; versus quot;switchquot;(“如果与“开关相比)
问题描述
可能重复:
是“else if”比 “switch() case” 更快?
我最近遇到很多情况,我的条件非常简单,需要分支应用程序流.完成我正在做的事情的最简单"方法只是一个普通的旧 if
/elseif
语句:
I've encountered a lot of situations lately where I have very simple conditionals and need to branch application flow. The "simplest" means of accomplishing what I'm doing is just a plain old if
/elseif
statement:
if($value == "foo") {
// ...
} elseif($value == "bar") {
// ...
} elseif($value == "asdf" || $value == "qwerty") {
// ...
}
...但我也在考虑类似的事情:
...but I'm also considering something like:
switch($value) {
case "foo":
// ...
break;
case "bar":
// ...
break;
case "qwer":
case "asdf":
// ...
}
这似乎不太可读,但也许它的性能更高?但是,当条件中的或"表达式越来越多时,switch语句似乎更具可读性和实用性:
This seems a little less readable, but perhaps it's more performant? However, when there are more and more "or" expressions in the conditional, it seems that the switch statement is much more readable and useful:
switch($value) {
case "foo":
// ...
break;
case "bar":
case "baz":
case "sup":
// ...
break;
case "abc":
case "def":
case "ghi":
// ...
break;
case "qwer":
case "asdf":
// ...
}
我还看到了使用数组和函数对代码流进行分支的选项:
I've also seen options where code flow is branched using arrays and functions:
function branch_xyz() {/* ... *
本文标题为:“如果"与“开关"相比


- SoapClient 设置自定义 HTTP Header 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- Laravel 仓库 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01