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() {/* ... *
本文标题为:“如果"与“开关"相比


基础教程推荐
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01