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

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

问题描述

哪个更好最快的方法是: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 通常会使感觉.如果超过例如,我也只会使用 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() 只被调用一次,而 with

Then some_func() is only called once while with

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

它将被调用两次 - 包括函数调用发生两次可能产生的副作用.但是,您始终可以使用 $res = some_func(); 然后在您的 if 条件中使用 $res - 这样您就可以避免这个问题总之.

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 的一种情况是当您有更复杂的条件时 - switch 仅适用于 x == yy 是一个常数值.

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 还是 if else if?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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