Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
464 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your first example is simply wrong. You need elseif instead of just else.

If you use if..elseif... or switch is mainly a matter of preference. The performance is the same.

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.

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;
}

Then some_func() is only called once while with

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...