Multiple foreach vs multiple if inside foreach
-
05-06-2021 - |
Question
Which would be more optimal of the two? I can't test it on my computer, I can't rely on it.
foreach($links as $link){
if($a){
//do something
}
if($b){
//do something
}
if($c){
//do something
}
if($d){
//do something
}
}
OR:
if($a){
foreach($links as $link){
//do something
}
}
if($b){
foreach($links as $link){
//do something
}
}
if($c){
foreach($links as $link){
//do something
}
}
if($d){
foreach($links as $link){
//do something
}
}
La solution
I think The first one is better. Let's say $a === true
and $b === true
. In the first example only one loop will be executed, but on the second example the same loop will be executed twice.
Autres conseils
this would depend on the likelihood of each condition being true, and the length of the collection you're looping through. The overhead of IF condition would be small, but would add up over a large collection, whereas the overhead of the foreach iterator is slightly higher, but can be minimised if some of these conditions are rarely true
If the conditions are very similar, it may be easier to read with either a switch()
statement, or if $a, $b, $c and $d are mutually exclusive, using elseif
.
The two snippets of code do not do the same thing and you should therefore use the one which is correct, and not choose merely on grounds of speed.
To see this, consider what happens if more than one of the $a, $b
, etc is true. The two snippets will both execute lots of do somethings
, but in a different order.
Also consider the difference if the do somethings
may change th values of $a, $b
, etc.
1 loop is always better than (potentially) 4.