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?
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
.
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.
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