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:
- Unset your variables. This frees up a surprising amount of memory
- Use memcache
- Turn on apache’s mod_deflate
- If your database is local then close your connections when you’re done with them
- If your database is remote then use persistant connections
- 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. -
Use string concatenation instead of embedding variables in strings.
$some_string = "asdf $asdf2 asdf"; //bad $some_string = 'asdf '.$asdf2.' asdf'; //good
-
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
- 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
- Not everything needs to be an object. There is a fair amount of overhead when doing everything OOP.
- Use output buffering to make everything seem faster.
Hopefully I didn’t miss any of the big ones.