Optimising “For” Loops [TotD]

Posted by hts | December 30, 2007 .

From now on, I’ll (try to) post, every day, a quick tip, usually regarding PHP programming. (TOTD= tip of the day)

So for today, I’ll show you how to optimise your application speed with a simple trick regarding FOR loops in PHP:

Problem

Lets take the following example:

<?php
//let's suppose $max and $min variables are pulled from a database
for ($i=1;$i< ($max-$min);$i++) {
      
//do something
}
?>

This is inefficient, unoptimised, memory and CPU consuming, etc - you name it.
And why is that? Because, every time the loop is called / executed, the value of $max-$min must be calculated.
This is a simple operation - but what if we would have a complex operation? That would increase the execution time for your script - a lot.

Solution:

Create another variable in which you store the value you need to use there.
For example:

<?php
//let's suppose $max and $min variables are pulled from a database
$diff=$max-$min;
for (
$i=1;$i<$diff;$++) {
      
//do something
}
?>

That’s it, now your “FOR” loops are optimised! Happy coding!

Leave a Comment

If you would like to make a comment, please fill out the form below.

Name (required)

Email (required)

Website

Comments

2 Comments so far
  1. Mike January 3, 2008 8:36 pm

    I really like the idea of the TotD. I am currently learning PHP now so I think this will help me a lot, thanks for the help.

  2. hts January 3, 2008 10:14 pm

    Glad to hear these quick tips are useful. If you haven’t already, make sure to subscribe to the RSS feed so that you’ll never miss a tip.