哪个更快更好,Switch Case还是其他如果? [英] Which is Faster and better, Switch Case or if else if?

查看:163
本文介绍了哪个更快更好,Switch Case还是其他如果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪种方法更好更快:if或switch?

Which is the better and fastest methods : if or switch ?

if(x==1){
  echo "hi";
} else if (x==2){
  echo "bye";
}

switch(x){
  case 1
    ...
  break;
  default;
} 


推荐答案

你的第一个例子是完全错误的。您需要 elseif 而不是 else

Your first example is simply wrong. You need elseif instead of just else.

如果你使用 if..elseif ... switch 主要是偏好问题。性能是相同的。

If you use if..elseif... or switch is mainly a matter of preference. The performance is the same.

但是,如果您的所有条件都是 x == value 类型 x 在各种条件下都相同, switch 通常都有意义。我还只使用开关如果超过例如两个条件。

However, if all your conditions are of the type x == value with x being the same in every condition, switch usually makes sense. I'd also only use switch if there are more than e.g. two conditions.

如果变量部分是函数调用, switch 实际上给你带来性能优势的情况:

A case where switch actually gives you a performance advantage is if the variable part is a function call:

switch(some_func()) {
    case 1: ... break;
    case 2: ... break;
}

然后 some_func()仅用

if(some_func() == 1) {}
elseif(some_func() == 2) {}

它将被调用两次 - 包括函数的可能副作用打电话发生两次。但是,您总是可以使用 $ res = some_func(); 然后在<$ c $中使用 $ res c>如果条件 - 所以你可以完全避免这个问题。

it would be called twice - including possible side-effects of the function call happening twice. However, you could always use $res = some_func(); and then use $res in your if conditions - so you can avoid this problem alltogether.

不能使用switch的情况一切都是因为你有更复杂的条件 - 开关仅适用于 x == y y 是一个常数值。

A case where you cannot use switch at all is when you have more complex conditions - switch only works for x == y with y being a constant value.

这篇关于哪个更快更好,Switch Case还是其他如果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆