Hello,
Does a switch or If statement quick to execute, where there are atleast 10-20 conditions
Thanks Dave
Hello,
Does a switch or If statement quick to execute, where there are atleast 10-20 conditions
Thanks Dave
This person benchmarked it and came to the conclusion that "if/else was slightly better." Code and benchmarks included.
This benchmark concluded that they are approximately equivalent.
Might be a slight difference to use one over the other, but for 10-20 conditions I think a switch case might be more readable and better suited.
I've always been taught that for more than 4 or 5 conditions you should use almost always use switch over if / else / else if structures - I might be wrong though.
I look with doubt at the (first) link Jordan provided, I think that when used appropriately switch should be slightly faster, I've no hard data to back it up but you can always benchmark it yourself. One scenario when you should never use switch is when you need to make strict (===) comparisons for instance.
Anyway, the point being that this is micro-optimization, and I prefer having a readable, nice (girl-style) code at the possible expense of 0.000001 second than an ugly one.
For 10-20 conditions you should definitely use switch IMO.
Without further knowledge about the nature of the problem, I would guess that you are clearly optimizing the wrong thing here.
The only situation where the speed of the conditional would be relevant if you were looping over a large dataset and deciding about doing different things depending on the content of one specific datafield.
If you are doing a lot of things with each dataset then the cost of the condition should be irrelevant to the speed of every single loop iteration and you should definitely optimize for readability and use the switch statement.
if you are doing very little in each iteration but have to do it a million times, then you should maybe go about it in a different way:
foreach($alldata as $index => $dataset)
{
$function_to_call = 'handle_'.$dataset->switching_value;
if (function_exists($function_to_call))
$function_to_call($dataset);
}