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

后端 未结 8 1235
予麋鹿
予麋鹿 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:27

    I found this post: https://gist.github.com/Jeff-Russ/2105d1a9e97a099ca1509de1392cd314 which indicates switch/case to be faster than if/elseif with ===.

    They also indicate nested if statements which makes a lot more sense and also provide far better results.

    Their times:

    nested if/elseif === : 0.25623297691345 (NESTED IF)

    switch/case : 0.33157801628113 (SWITCH CASE)

    if/elseif with === : 0.45587396621704 (FLAT IF)

    only if with === : 0.45587396621704 (ONLY IF)

提交回复
热议问题