PHP Performance and Efficiency Research
After researching about PHP performance and efficiency optimization, I have these important things to focus on:
- Profiling the PHP code
- Upgrading to latest stable PHP
- Responsible Caching
- Avoid useless functions and variables
- Avoid multiple SQL queries (specially for remote databases)
- Understand PHP features like garbage collection
- Using functions and constructs properly
Profiling your PHP code to pinpoint bottlenecksBefore trying to optimize your PHP code, you have to know which part of your code is the slowest. To find this out you have to profile your code.
profiling ("program profiling", "software profiling") is a form of dynamic program analysis that measures, for example, the space (memory) or time complexity of a program, the usage of particular instructions, or frequency and duration of function callsBy this you will know where your bottlenecks(i.e. components that slows down the whole system) are and start optimizing them.
A bottleneck is a phenomenon where the performance or capacity of an entire system is limited by a single or limited number of components or resources.Bottlenecks could be a bad regular expression on a preg_match, a very long iteration (e.g. foreach, for, while), a bad SQL query on a mysql_query, a connection(e.g. cURL) to a non-responding server or even infinite loop. Usually this could be fixed by code optimization, but in some cases you really have to do some caching to relieve the load.
The team of developers who maintain the PHP engine have made a number of significant performance improvements over the years. If your web server is still running an older version, such as PHP 3 or PHP 4, you may want to investigate upgrading before you try to optimize your code.In my experience I only upgrade to have bugs fixed and have new features, as for performance, I don't notice much difference between versions. About every month there is a new minor version release found on PHP download page. Or you can also do an upgrade using the package manager(e.g. apt-get upgrade) (configuration maybe needed)
cache is a component that transparently stores data so that future requests for that data can be served fasterNot just caching, you have to do it responsibly. Finding a way to do this accurately and efficiently at the same time is sometimes profound but sometimes tricky. It depends on the situation. For example, Smarty, a popular templating engine have found an accurate way to compile the templates, which renews every time one of the template files involved is modified. There's a lot of things to cache according to your application, here are some examples
- static database tables - those tables that you do not update too often (e.g. categories)
- static pages
- static includes