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; }
In general, "else if" style can be faster because in the series of ifs, every condition is checked one after the other; in an "else if" chain, once one condition is matched, the rest are bypassed.
A switch statement works much faster than an equivalent if-else ladder. It's because the compiler generates a jump table for a switch during compilation. As a result, during execution, instead of checking which case is satisfied, it only decides which case has to be executed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With