PHP Best Practices in Performance – Part 1
After PHP best practices in Security – Part 1 and Part 2, here’s the first post of the series about PHP best practices in Performance.
1. If you want to output a basic string, you’d better use single quotes, instead of double quotes. If you use a string surrounded by double quotes, it’s parsed by the PHP interpreter for special characters and variables. So, use single-quoted strings every time it’s possible.
2. When it’s possible do not use global variables. The reason is that incrementing a global variable is two times slow than a local variable.
3. If you use full paths in requires and includes, it’ll cost less time on resolving the OS paths.
4. You can save time if you avoid repeating function calls in loops:
$str = ‘Imagine it is a very long string …’;
for ($i = 1; $i < = strlen($data); $i++) {
…
}
It’ll be faster:
$str = ‘Imagine it is a very long string …’;
$strLen = strlen($data);
for ($i = 1; $i < = $strLen; $i++) {
…
}
5. It’s good to know that methods in derived classes run faster than methods defined in the base class.
6. Each object in PHP consumes a lot of memory. So, not every data structure should be implemented as a class. You can use arrays, too.
7. when you’re done with database statements, close your database connections.
8. PHP internal functions are faster that functions written in userland. So, before implementing a basic functionality, you’d better check if it already exists in PHP.

One Comments to “PHP Best Practices in Performance – Part 1”
1. Is a myth. Ouput buffering and other stuff have much more impact than that.
2. Micro optimization. You can use global variables for caching global application stuff.
3. Correct. Best practice is to define a constant like “DIR_INC”.
4. Correct. Check out my loop battle :D
http://juliusbeckmann.de/blog/php-foreach-vs-while-vs-for-the-loop-battle.html
7. Persistent database connections are normally faster and should NOT be closed! Although a not persistent connection will always be closed on script end.