Differencebetween Switch-Case and If-Else in PHP

What is the difference between Switch-Case and If-Else in PHP?

Interesting question because in a compiled languaged (or JIT'ed language even) there is a nice performance gain when using switch statements because the compiler can build jump tables and will run in constant time. Even switching on a string can be optimized as the string can be hashed. However, from what I've read, it appears php makes no such optimization (I'm assuming because it's interpreted and runs line by line).

Great .Net article about switch optimization: If vs. Switch Speed

Regarding php being interpreted, the PHP docs says: http://php.net/manual/en/control-structures.switch.php

It is important to understand how the switch statement is executed in
order to avoid mistakes. The switch statement executes line by line
(actually, statement by statement). In the beginning, no code is
executed. Only when a case statement is found with a value that
matches the value of the switch expression does PHP begin to execute
the statements. PHP continues to execute the statements until the end
of the switch block, or the first time it sees a break statement. If
you don't write a break statement at the end of a case's statement
list, PHP will go on executing the statements of the following case.

I also found several references all suggesting that if / else statements in php may actually be faster than switch statements (weird). This probably is not true if you compile php (something I've never done, but apparently it's possible).

http://www.fluffycat.com/PHP-Design-Patterns/PHP-Performance-Tuning-if-VS-switch/

This article in particular, http://php100.wordpress.com/2009/06/26/php-performance-google/, is interesting as the author compares internal php code of if vs switch and they are nearly identical.

Anyways, I would say that any performance gain will be insignificant one way or the other, so it's more of a user preference. If statements are more flexible and you can more easily capture ranges of values (especially large ranges) as well as do more complex comparisons whereas switch statements line up to exactly one value.

What is the difference between Switch and IF?

Or any performance wise difference between two??

Forget about the performance difference on this level- there may be a microscopic one, but you'll feel it only when doing hundreds of thousands of operations, if at all. switch is a construct for better code readability and maintainability:

switch ($value) 
{
case 1: .... break;
case 2: .... break;
case 3: .... break;
case 4: .... break;
case 5: .... break;
default: .... break;
}

is mostly much more clean and readable than

if ($value == 1) { .... }
elseif ($value == 2) { .... }
elseif ($value == 3) { .... }
elseif ($value == 4) { .... }
elseif ($value == 5) { .... }
else { .... }

Edit: Inspired by Kuchen's comment, for completeness' sake some benchmarks (results will vary, it's a live one). Keep in mind that these are tests that run 1,000 times. The difference for a couple of if's is totally negligeable.

  • if and elseif (using ==) 174 µs
  • if, elseif and else (using ==) 223 µs
  • if, elseif and else (using ===) 130 µs
  • switch / case 183 µs
  • switch / case / default 215 µs

Conclusion (from phpbench.com):

Using a switch/case or if/elseif is almost the same. Note that the test is unsing === (is exactly equal to) and is slightly faster then using == (is equal to).

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.

PHP switch statement VS if elseif statement benchmark

Whether you get exactly the same results will vary based on what conditions you are evaluating, your equipment, settings, and other factors. But yes, generally if/elseif/else with strict comparison (===) will outperform switch. The reason is that switch uses "loose" (i.e., type-insensitive) comparison (==), which is slower than type-sensitive comparison (===).

Keep in mind that these differences are extremely tiny and are going to be dwarfed by any inefficiencies in your algorithm. So, you should only tune for details like this after you are sure you have eliminated other major bottlenecks.

PHP: switch vs if

The performance aspect is completely irrelevant.

As PHPBench shows, even with 1,000 operations, the difference between the two is about 188 microseconds, that's 188 millionths of a second. PHP code usually has much bigger bottlenecks: a single database call will often take tens of milliseconds, that's tens of thousands of times more.

Use whichever you like, and whichever is better for your code's readability - for many checks, most likely the switch.

Difference between if and case

From logical point of view there is not much difference, both of them are conditional branching block.

Beside that, switch statement executes faster, as it knows all the branching where the jump has to made, while for the if statement the same is not true.

consider reading . . .

  1. "if" versus "switch"
  2. Is "else if" faster than "switch() case"?
  3. If-else vs switch – Which is better?

Conditional switch statements in PHP

I think you're searching for something like this (this is not exactly what you want or at least what I understand is your need).

switch (true) finds the cases which evaluate to a truthy value, and execute the code within until the first break; it encounters.

<?php

switch (true) {

case ($totaltime <= 1):
echo "That was fast!";
break;

case ($totaltime <= 5):
echo "Not fast!";
break;

case ($totaltime <= 10):
echo "That's slooooow";
break;
}

?>

When to use If-else if-else over switch statements and vice versa

As with most things you should pick which to use based on the context and what is conceptually the correct way to go. A switch is really saying "pick one of these based on this variables value" but an if statement is just a series of boolean checks.

As an example, if you were doing:

int value = // some value
if (value == 1) {
doThis();
} else if (value == 2) {
doThat();
} else {
doTheOther();
}

This would be much better represented as a switch as it then makes it immediately obviously that the choice of action is occurring based on the value of "value" and not some arbitrary test.

Also, if you find yourself writing switches and if-elses and using an OO language you should be considering getting rid of them and using polymorphism to achieve the same result if possible.

Finally, regarding switch taking longer to type, I can't remember who said it but I did once read someone ask "is your typing speed really the thing that affects how quickly you code?" (paraphrased)



Related Topics



Leave a reply



Submit