Switch Case 或 if else if 哪个更快更好?

Which is Faster and better, Switch Case or if else if?(Switch Case 或 if else if 哪个更快更好?)
本文介绍了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 哪个更快更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)