PHP Code Optimization Tips
December 13th, 2007
Check out my other PHP optimization tips by clicking on the Optimization category.
Usually I’m a code performance freak. I like to squeeze every little milliseconds out of the code I’m writing.
Over the years I developed a sort of PHP code performance sense, this means I look at code and simply know that it can do better. I gathered some PHP performance tips, but never got the chance to share with other people, or on my blog. So I thought I will create a code benchmark category on this blog and slowly
I will post these performance tips along with results. As a starting did you knew that:
for ($i=0; $i<count($tmp_array); $i++)
{
//do something...
}
Is almost 60% slower than:
$c = count($tmp_array);
for ($i=0; $i<$c; $i++)
{
//do something...
}
This is because on each iteration the php function count counts the same array over and over again


Comments
December 14th, 2007
I’m pretty sure if you pre-increment instead of post-increment, that will be faster as well.
Also, if you perform a do while instead of a for, the initial conditional check in the for loop is skipped for a little extra gain.
December 14th, 2007
Yes, I will write more tips in detail, this was just an introductory little code snippet.
December 17th, 2007
[...] Code Optimization #1 and [...]
August 22nd, 2008
I dislike spurious variable. If you are going to go over every element, why not rely on foreach :
foreach (array_expression as $value)
or
foreach (array_expression as $key => $value)
http://ca.php.net/manual/en/control-structures.foreach.php
August 23rd, 2008
A really classical example :-)! I have never measured the difference in performance though.
August 23rd, 2008
http://www.phpbench.com/
August 23rd, 2008
@Adam Żochowski: foreach makes a copy of the array it is going to run through, so it has a delay for making that particular copy. foreach is a very convenient and short way to iterate through associative arrays, and I love it too, but it just hasn’t got a very good name for speed.
August 24th, 2008
You’re writing about code performance but I don’t see any benchmarks. If you’re advocating something is faster, we want to see the numbers.
August 24th, 2008
If you check out phpbench.com (the for-loop test) you can see it for yourself.