Jun 26 2009

Make Your PHP Faster

I was reading about some php performance tips at work today and decided to throw together some of the ways to make your php site faster.

Here’s a couple of short tips to avoid making your site lag for the user:

  1. Unset your variables. This frees up a surprising amount of memory
  2. Use memcache
  3. Turn on apache’s mod_deflate
  4. If your database is local then close your connections when you’re done with them
  5. If your database is remote then use persistant connections
  6. Don’t use functions inside of a for loop control expression unless absolutely necessary. Example :
    
    for($i=0;$i<some_big_calculation(20);$i++)
    

    The some_big_calculation function will be called every iteration.
  7. Use string concatenation instead of embedding variables in strings.
    
    $some_string = "asdf $asdf2 asdf"; //bad
    $some_string = 'asdf '.$asdf2.' asdf'; //good
    
  8. When including files, use at least a relative path so PHP doesn’t have to look in the entire path.
    
    include("./some_file.php"); // looks in the current directory
    include("wrong.php"); // searches every directory in the path
    
  9. Try not to use include_once or require_once. They are more expensive and it really isn’t that hard to only include files once
  10. Not everything needs to be an object. There is a fair amount of overhead when doing everything OOP.
  11. Use output buffering to make everything seem faster.

Hopefully I didn’t miss any of the big ones.

Share