What is quickest? To do a condition based on a variable outside the loop inside a loop or outside, or does it even matter (does the compiler do it for you), or should you maybe use a completely different workaround?
Example #1 with the condition inside the loop (a single foreach):
$test = 2;
foreach ($list as $listItem) {
if ($test == 1) {
$listItem .= " - one";
} else if ($test == 2) {
$listItem .= " - two";
} else if ($test == 3) {
$listItem .= " - three";
}
}
Example #2 with the condition outside the loop (quite ugly with multiple foreach’s):
$test = 2;
if ($test == 1) {
foreach ($list as $listItem) {
$listItem .= " - one";
}
} else if ($test == 2) {
foreach ($list as $listItem) {
$listItem .= " - two";
}
} else if ($test == 3) {
foreach ($list as $listItem) {
$listItem .= " - three";
}
}
As you probably could’ve guessed, example #2 is quicker, and the compiler doesn’t do it for you.
Overview
Performance tests
Example #1, condition inside of loop:
And the code:
Example #2, condition outside of loop:
And the code:
Alright, that’s a pretty obvious win for conditions outside of loops, but what if we try to compare with a boolean instead of an int?
Example #3, condition inside of loop, but conditioning with a boolean instead:
And the code:
Interesting. What if we use a built in function such as
array_walk?Example #4,
array_walk:And the code:
What?! You might think an inbuilt function would abstract it over a C or C++ function, and it might very well, however the problem is that the function calls make this method very very slow.
Pros/cons
Example #1 pros
Example #1 cons
Example #2 pros
Example #2 cons
Example #3 pros
Example #3 cons
Example #4 pros
Example #4 cons
globalall variables from the global scope.Conclusion
The PHP compiler doesn’t do it for you, and if you want performance you should go for example #2, however this test is made with an array that has a million entries. Chances are that your array isn’t going to have that many entries, and therefore you might go with example #1 or example #3 instead. Oh, and do not go for example #4.