PHP Code Optimization Tips

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
  1. coder
    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.

  2. Gyorgy Fekete
    December 14th, 2007

    Yes, I will write more tips in detail, this was just an introductory little code snippet.

  3. [...] Code Optimization #1 and [...]

  4. Adam Żochowski
    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

  5. Mike Borozdin
    August 23rd, 2008

    A really classical example :-)! I have never measured the difference in performance though.

  6. buggedcom
    August 23rd, 2008
  7. Valentin Bora
    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.

  8. klevo
    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.

  9. Gyorgy Fekete
    August 24th, 2008

    If you check out phpbench.com (the for-loop test) you can see it for yourself.

Leave your reply
  • (required)
  • (will not be published)
  • Show
    :mrgreen: :neutral: :twisted: :arrow: :shock: :smile: :???: :cool: :evil: :grin: :idea: :oops: :razz: :roll: :wink: :cry: :eek: :lol: :mad: :sad: 8-) 8-O :-( :-) :-? :-D :-P :-o :-x :-| ;-) 8) 8O :( :) :? :D :P :o :x :| ;) :!: :?:
  • Allowed tags: <a href="" title="">, <b>, <i>, <strike>, <em>, <strong>, <code>