4

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?

Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90
user2261839
  • 61
  • 1
  • 3

3 Answers3

23

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.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • +1 for the proof! otherwise -1 :) –  Apr 09 '13 at 13:29
  • +1 and comparing switch with if is meaning less ... but yes we can terminate if in some case and use switch so that it will be less complex and finely yes its depends on switchwation – NullPoiиteя Apr 09 '13 at 13:45
2

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.

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
1

Its not about performance, its more about requirement !!

Sometimes you want something to happen in your if condition, else, it'll go to else.

Switch can be used if you have a lot values to be compared

Deepanshu Goyal
  • 2,738
  • 3
  • 34
  • 61