Switch or If statement faster in PHP and why

Whether a switch or if statement is executed quickly, where there are at least 10-20 conditions

Thanks Dave

+4
source share
4 answers

This person compared him and came to the conclusion that "if / it was still a little better." Code and benchmarks included.

This test concluded that they are roughly equivalent.

+3
source

There may be a slight difference in using one over the other, but for 10-20 conditions, I think the switching case may be more readable and more appropriate.

+2
source

I've always been taught that for more than 4 or 5 conditions you should almost always use switch over if / else / else if structures. Maybe I'm wrong.

I look with alarm at the (first) link provided by Jordan, I think that if used properly, the switch should be a little faster, I don't have hard data to back it up, but you can always compare it yourself. One scenario where you should never use switch is when you need to make strict ( === ) comparisons, for example.

In any case, the fact is that this is micro-optimization, and I prefer to have a readable, pleasant (girl's style) code at a possible expense of 0.000001 seconds than ugly.

For 10-20 conditions, you should definitely use switch IMO.

+1
source

Without further knowledge of the nature of the problem, I would assume that you are clearly optimizing the wrong thing here.

The only situation where the speed of the conditional value would be relevant if you were fixated on a large data set and decided to do different things depending on the contents of one particular data field.

  • If you do many things with each data set, then the cost of this condition should not be relevant for the speed of each individual iteration of the loop, and you should definitely optimize for readability and use the switch statement.

  • if you do very little at each iteration, but have to do it a million times, then you should go differently:

    • Transfer bulk conversions to the source database using SQL if the data comes from the database.
    • sort all data by the switch value, and then process each subset separately
    • it may be faster to call another function for each other datapoint as follows:

  foreach($alldata as $index => $dataset) { $function_to_call = 'handle_'.$dataset->switching_value; if (function_exists($function_to_call)) $function_to_call($dataset); } 
  • or maybe it won’t - but still - tell us about a specific situation or think about optimizing something else if all this is not a bottleneck.
+1
source

Source: https://habr.com/ru/post/1299227/


All Articles