
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:
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.
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!
If you would like to make a comment, please fill out the form below.
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.
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.