PHP application performance tuning
Posted by Stanislav Furman on March 15, 2012Hello 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.
- Avoid global variables!
- Incrementing a local variable in a function is faster than incrementing a global variable.
- Incrementing an undefined local variable is much slower than a pre-initialized local variable.
- Incrementing an object property is slower than incrementing a local variable.
- Unset your variables when you don't need them any more, to free memory, especially large arrays.
- Function "echo" is faster than "print".
- Use apostrophes in echos/prints instead of quotes if it's possible - it will work faster.
- Use echo’s multiple parameters instead of string concatenation ( i.e. echo($str1,$str2); ).
- Avoid using regular expressions if you can use string functions such as stristr, strncasecmp, stripos, etc.
- Close your database connections as soon as you are done with them.
- Use apostrophes for array keys: $arr['id'] is faster than $arr[id].
- Don't use multi "if{} else if{}" statements, use Switch/Case statement instead.
- Error suppression with "@" slows down the performance.
- 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.
- If possible, avoid magics functions such as __get(), __set(), __call(), etc.
- Use require() and include() instead of require_once() and include_once() because "_once" function do a check if file was not inculded yet.
- Use full paths in include() and require(), it will take less time on resolving the OS paths.
- Apache handles static HTML much faster than PHP scripts, therefore it makes sense to use caching mechanisms (file caching, Memcache, Redis, etc).
- Use PHP accelerators to speed up the performance of your web site.
- 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