PHP: switch vs if

Which form is more effective

This:

switch($var) { case 1: break; case 2: break; } 

.. or this one:

 if( $var === 1 ) { } elseif( $var === 2 ) { } 

in terms of performance?

+4
source share
3 answers

The performance aspect is absolutely irrelevant.

As PHP Bench shows, even with 1000 operations, the difference between them is about 188 microseconds, which is 188 millionths of a second. PHP code usually has much larger bottlenecks: a single database call often takes tens of milliseconds, which is tens of thousands of times larger.

Use what you like and depending on what is best for your readability of the code - for many checks, most likely switch .

+22
source

Performance at such a microscale does not matter. Use one that is more appropriate in your context. Readability and maintainability are far more important than performance.

+2
source

It's not about performance, its more about demand !!

Sometimes you want something to happen in your if state, otherwise it will go into another.

A switch can be used if you have many values ​​to compare.

+1
source

All Articles