本文介绍了“如果"与“开关"相比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
是“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() {/* ... *
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!