Tips for speeding up php scripts

Tagged:  

Taken from

Programming PHP, 2nd Edition

By Rasmus Lerdorf, Peter MacIntyre, Kevin Tatroe

Optimizing Execution Time
Here are some tips for shortening the execution times of your scripts:

  • Avoid printf( ) when echo is all you need.
  • Avoid recomputing values inside a loop, as PHP's parser does not remove loop invariants. For example, don't do this if the size of $array doesn't change:
    for ($i=0; $i < count($array); $i++) { /* do something */ }

    Instead, do this:
    $num = count($array); for ($i=0; $i < $num; $i++) { /* do something */ }

  • Include only files that you need. Split included files to include only functions that you are sure will be used together. Although the code may be a bit more difficult to maintain, parsing code you don't use is expensive.
  • If you are using a database, use persistent database connectionssetting up and tearing down database connections can be slow.
  • Don't use a regular expression when a simple string-manipulation function will do the job. For example, to turn one character into another in a string, use str_replace( ), not preg_replace( ).

Optimizing Memory Requirements
Here are some techniques for reducing the memory requirements of your scripts:

  • Use numbers instead of strings whenever possible:
    for ($i="0"; $i < "10"; $i++) // bad for ($i=0; $i < 10; $i++) // good
  • When you're done with a large string, set the variable holding the string to an empty string. This frees the memory to be reused.
  • Only include or require files that you need. Use include_once and require_once instead of include and require.
  • If you are using MySQL and have large result sets, consider using the MySQL-specific database extension, so you can use mysql_unbuffered_query( ). This function doesn't load the whole result set into memory at onceinstead, it fetches it row by row, as needed.
  • Release MySQL or other database result sets as soon as you are done with them. There is no benefit to keeping result sets in memory beyond their use.