Saving the world from bad PHP
As I mentioned before, I’ve really taken a liking to the Columbus library system. Well, some of the books that I requested have been arriving and I just speed-read one called Spring into PHP 5. I now realize that I’ve reached the point in my knowledge of PHP that bad programming just leaps off a page or a computer screen. I can’t help but notice it immediately. Let’s look at a glaring example from this book.
Check out this handy script from the section about looping over arrays.
$fruits[0] = "pineapple";
$fruits[1] = "pomegranate";
$fruits[2] = "tangerine";
for ($index = 0; $index < count($fruits); $index++) {
echo $fruits[$index], "\n";
}
This may look fine, but there is a serious performance issue lurking in the test condition of the for loop. The PHP function count( ) returns the number of elements in an array. In nearly all cases, that number will not change while looping through all of them. So what is the point of calling the function over and over again every time you test to see if you've reached the end of the array?! Granted, in this particular case it's not as important because the array only has three elements. However, arrays commonly hold hundreds of elements or more. This bit of code uses one unnecessary function call for each element in the array!
"Okay, smart guy," you say. "How would you fix it?"
"Easy," I reply. "Like this..."
$fruits[0] = "pineapple";
$fruits[1] = "pomegranate";
$fruits[2] = "tangerine";
$fruitCount = count($fruits);
for ($index = 0; $index < $fruitCount; $index++) {
echo $fruits[$index], "\n";
}
Using count( ) before the for loop starts allows us to store the array size in a variable called $fruitCount and just test against that variable while looping through the array. If the array contains 1000 elements, we just saved ourselves 1000 function calls. Multiply that by 100,000 page views and, well, you get the idea…
Moonlighting as a technical reviewer for computer books is actually something that I would love to do. I tried to get my foot in the door once, but nothing ever came of it. Maybe it’s time to take another shot. Think of all the unsuspecting neophyte programmers I could save from bad practices like the one I just illustrated. And don’t even get me started on SQL injection attacks. Sheesh…
Sphere: Related ContentComments
One Response to “Saving the world from bad PHP”
Leave a Reply
Duh, everyone knows that. In Javascript though, that’s not an error as you access the count of an array by using arrayVariable.size, which automatically updates as you add and delete items from the array… But most importantly, isn’t calculated on each iteration of a loop.