Yesterday’s article actually got me a little amped up about coding conventions – Comparing a while loop against a foreach loop of an array – because I never thought I would actually have to do a comparison between a while loop and a foreach loop on an array! If we go back and revisit the post, I was reviewing a recent CakePHP commit for an optimization on the Hash class. The code in question is three separate blocks of code that leverage the array_shift function to get the next value in the array with a foreach loop instead.
I truly have no preference in any style, but what I do ask is that you at least pick one style yourself! Here is the original code in question:
The first loop through the $parts array is done as follows:
[code]
while (($key = array_shift($parts)) !== null) {
…
}
[/code]
A little bit further down the file, the $tokens array is looped through like this:
[code]
do {
$token = array_shift($tokens);
…
} while (!empty($tokens));
[/code]
And finally even further down in the file, the $conditions array is looped through as follows:
[code]
$ok = true;
while ($ok) {
if (empty($conditions)) {
break;
}
$cond = array_shift($conditions);
…
}
[/code]
<rant>
Seriously? I’m a little speechless after just pasting this code into the post… As a noted in yesterday’s post, switching to a foreach loop saw about a 25% speed improvement, but put that aside and just look how inconsistent this code is!
I think a little props should go out to jrbasso for reconciling this code to use a standard format. I’ve never committed to an open source project before, but I think if I ever looked that closely at code I would be forced too!
Please folks, I don’t care what your standard is, just pick one and stick to it or more important, if a standard is already being used, stick to it as well – or change them all to match.
</rant>