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 PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何替换eregi() 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01