Benchmark and optimize PHP script speed

17 February 2011

I found out the hard way why speed optimization in PHP is very important. Part of my work is developing a very complex digital learning system (Mind2Mind) and this product has had it's first run a while ago. During the time the users in the system had grown from more than 3000 and more than 8000 usergroups. When this happened we found out the system didn't handle large numbers of users very well.

Through this, i learned that it is very important to start optimizing your code from the beginning of the project and apply a few best practices to speed up a script. A script that takes 0,01 second doesn't seem very long, but if you multiply this by 8000, it takes 80 seconds (!!!) to render a page...

Benchmark

In my experience it is the hardest part to find wich part of a existing script is slowing the page down. In my case i thought it was somewhere at the end of the page, but later it turned out to be in the beginning of the page, when initializing the classes. Looking in the wrong place can cost you a lot of time!

One option is to comment everything in a page, and uncomment all the lines one by one. When the page slows down, you found the line where the slow part is.

But sometimes this isn't enough (not in my case) and you want to know how long a particular part of the script takes to execute. The second option is to devide te script in parts (not literly) and time the parts. If that isn't enough you can place a timer "around" every function or line, to get exact details on wich part of the page takes how much time to execute.

I use this script to do this:
<?php
function getTime() {
    $timer = explode( ' ', microtime() );
    $timer = $timer[1] + $timer[0];
    return $timer;
}
?>

And in a sample of code i use it this way:
<?php
$start = getTime();
    $aUsers = $wms->getUsers( 0, $showType, true, ($_REQUEST['page']*$perPage), $perPage );
$end = getTime();
echo  '<strong>getUsers/getUsersByAbc</strong>: '.round($end - $start,4).' seconden<br />';
?>

In line 1 the starting time is stored in $start. In line 2 the funciton is executed and in line 3 the ending time is stored in $end. At last in line 4 a string is displayed with the time it took to execute the function (rounded at 4 decimals).

Optimizing
Now you found where the slowness is, you can apply these best practices:

  • Usestatic methods when possible, this is 4 times faster
  • Echo is faster as print
  • Use , instead of . to concatinate a string
  • Set the max value in a for-loop before the loop, not in the if statement.
  • $max = count($array);
    for ($i=0;$i<$max;$i++) {
    echo $i;
    }
  • Unset vars to clear memory (especially when using arrays)
  • Use full paths in includes and requires, so the server doesn't have to resolve the paths for you
  • Use strncasecmp, strpbrk and stripos in stead of regex
  • It's better to use a select statement then multiple if statements with multiple else statements
  • Suppress errors with an @ is very slow
  • Close database connections when you don't need them anymore
  • $row['id'] is 7 times faster as $row[id]
  • Incrementing a global var is 2 times slower as a local var
  • Wrap your string in single quotes (') instead of double quotes (") is faster because PHP searches for vars in "..." and not in '..'
  • A PHP script is 2 to 20 times slower as a HTML page. Use HTML pages when possible.
  • PHP scripts are compiled everytime you call them. Use PHP caching software to gain a speed optimization of 25% to 100%.
  • $i++ is slower as ++$i
  • Not everything has to be OOP. Most of the time OOP is just overhead, so use it wisely!
  • Use as much of the default functions of PHP, you don't have te reinvent the wheel!

I found this list with best practices on the internet and printed it out once, but i can't find the source of it. Does somebody know where it came from, please let me know!
You must have JavaScript enabled to use this form!

Leave a comment!

  1. Your mail is safe with me. It's only only used to display your Gravatar image!

11 comments

Previous Page 1 of 2 Next
  1. Gravatar

    pat

    26 September 2017

    looks like you need to prove your saying ...

    specially the "Optimizing" section

  2. Gravatar

    adan

    17 August 2012

    more efficient:

    <?php
    function getTime() {
    $timer = microtime();
    $timer = explode( ' ', $timer );
    $timer = $timer[1] + $timer[0];
    return $timer;
    }
    ?>

  3. Gravatar

    RMC

    08 May 2012

    This list of optimizations seems to be outdated (for PHP5 at least). Check out http://www.phpbench.com/ for cool tests.

    Also, PHP5 has microtime(true) to return the seconds as (float).

  4. Gravatar

    Hari

    25 February 2012

    This is awsome Johan.
    One more request. Is there any tool to compress or optimize the php files.
    example remove all comments, extra spaces etc.,

  5. Gravatar

    cm

    28 December 2011

    check this:
    http://www.wmtips.com/php/tips-optimizing-php-code.htm

  6. Gravatar

    Photoshop Clipping Path

    31 October 2010

    Thanks for sharing this wonderful post

  7. Gravatar

    Kedar

    01 October 2010

    Please add some interesting tips for optimization in php that are less known and useful.

  8. Gravatar

    Kynist

    05 September 2008

    I learnt some new things for optimization. Thank you.
    A faster way for looping through an array (point 4 in your list) would be:

    $i = 0;
    while (isset ($array [$i])) {
    ++$i;
    }

    isset () is not a function, but a language construct!

  9. Gravatar

    Meint

    07 January 2008

    I think your list comes from a presentation by Rasmus Lerdorf regarding PHP optimisation and profiling

  10. Gravatar

    DreamDealer

    29 October 2007

    @MJH: thanks for the heads-up!

Previous Page 1 of 2 Next