Programming Tip: Healthy Iterations!

We, as programmers, often go on to write code that seems fine at the time of actually writing that chunk of code. But sometimes, we see that bit again to discover that we could actually optimize the code for better performance.

Below is some code which resembles something I wrote in PHP a while ago when working on one of my projects:

for ($i=0; $i<count($someArray); $i++) {
    print $someArray[$i];
}

At first glance, it might look like a nice & clean piece of code but a closer look is recommended. As you can see, the count($someArray) function is repeatedly called in all the iterations of the loop. This process puts a lot of stress on the PHP engine as compared to the alternative (and better) way. Whats the better way then you ask? Well, here it is:

$arrayLength = count($someArray);
for ($i=0; $i<$arrayLength; $i++) {
     print $someArray[$i];
}

As you can see, the function that counts the total number of elements in the array is called only once. That gives us a tremendous boost in the execution time. For a small site, this is not such a big issue I think. However, once you start getting more and more hits to your site, you should definitely look to optimize your code as much as possible.

Happy Coding!

~ by socialgeek on January 3, 2007.

Leave a Reply