PHP application performance tuning

Posted by Stanislav Furman  on March 15, 2012

Hello Coders!

In this article I will list a few advises on how to optimize your PHP web application performance. All these tips below I learned myself or from co-workers, blog articles and books. Keep in mind though that usually there is no need to go nuts when it comes to performance optimization. So, please don't open your IDE right away and don't try to use all tips together. Simply get an idea and note something that could be useful in your specific case.

  1. Avoid global variables!
  2. Incrementing a local variable in a function is faster than incrementing a global variable.
  3. Incrementing an undefined local variable is much slower than a pre-initialized local variable.
  4. Incrementing an object property is slower than incrementing a local variable.
  5. Unset your variables when you don't need them any more, to free memory, especially large arrays.
  6. Function "echo" is faster than "print".
  7. Use apostrophes in echos/prints instead of quotes if it's possible - it will work faster.
  8. Use echo’s multiple parameters instead of string concatenation ( i.e. echo($str1,$str2); ).
  9. Avoid using regular expressions if you can use string functions such as stristrstrncasecmpstripos, etc.
  10. Close your database connections as soon as you are done with them.
  11. Use apostrophes for array keys: $arr['id'] is faster than $arr[id].
  12. Don't use multi "if{} else if{}" statements, use Switch/Case statement instead.
  13. Error suppression with "@" slows down the performance.
  14. Do not use functions inside of loop functions (e.g. for ($x=0; $x < count($array); $x) {} ) because the count() function is called in each loop iteration and slows down performance.
  15. If possible, avoid magics functions such as __get(), __set(), __call(), etc.
  16. Use require() and include() instead of require_once() and include_once() because "_once" function do a check if file was not inculded yet.
  17. Use full paths in include() and require(), it will take less time on resolving the OS paths.
  18. Apache handles static HTML much faster than PHP scripts, therefore it makes sense to use caching mechanisms (file caching, Memcache, Redis, etc).
  19. Use PHP accelerators to speed up the performance of your web site.
  20. Avoid I/O operations or optimize it as much as possible if you need to you use it.

I hope you have found these web application performance tips useful. If you have any comments or have something to add, your feedback is very welcome!

Good luck with the performance tuning!

Leave your comment

Fields with * are required.

* When you submit a comment, you agree with Terms and Conditions of Use.