Which is Faster and better, Switch Case or if else if?
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.
According to phpbench.com, if/elseif is slightly faster, especially when using strict comparison (===).
But it'll only really matter if you want to shave off microseconds on a function that'll be called thousands of times.
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...