Which is Faster and better, Switch Case or if else if?

后端 未结 8 1249
予麋鹿
予麋鹿 2020-11-28 05:52

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;
          


        
8条回答
  •  感动是毒
    2020-11-28 06:09

    General rule is use switch whenever the number of conditions is greater than 3 (for readability).

    if / else if / else is more flexible (hence better), but switch is slightly faster because it just computes the condition once and then checks for the output, while if has to do this every time.

    EDIT: Seems like switch is slower than if after all, I could swear this was not the case...

提交回复
热议问题