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.

相关文章