Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: switch vs if [duplicate]

Which form is more efficient

This one:

switch($var) {
  case 1:

    break;
  case 2:

    break;
}

..or this one:

if( $var === 1 ) {

} elseif( $var === 2 ) {

}

in terms of performance?

like image 465
user2261839 Avatar asked Nov 27 '22 21:11

user2261839


2 Answers

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.

like image 145
Pekka Avatar answered Dec 16 '22 11:12

Pekka


Performance in such micro-scale doesn't matter at all. Use the one which is more suitable in your context. Readability & maintainability is far more important than performance.

like image 35
Mariusz Jamro Avatar answered Dec 16 '22 11:12

Mariusz Jamro