Performance of PHP based application, either script based or web based is a factor of configuration of PHP, web server, hardware infrastructure, network topology and most important, the quality of written code. It does not matter if you are running WordPress or any other custom PHP application you will have to consider all those factors to squeeze maximum performance.
What I can do to increase performance of PHP
There are many steps you can take to increase performance of your applications. There are two distinct ways that help boost performance: Software and Hardware. Let’s tackle both of those separately.
Software Configuration Based Enhancements
PHP used to be slow in the past but that is no longer the case. Even with all the improvements with each subsequent release of PHP, it is still not at part with the performance of languages such as C or C++. But that is not the use case for the language. PHP has its own strengths where traditional compiled languages cannot compete with it.
Enabling PHP OpCode Cache
PHP is not a compiled language in the traditional sense. During execution of the language the code is parsed and compiled into OpCode which is then executed in the virtual machine. Caching of the OpCodes helps significantly with increasing the performance of your application, or any application that is built using PHP.
In my testing I have found that enabling OpCode cache in PHP increases performance > 300% in most cases.
The benefits are available not only for web applications like WordPress for also for single scripts run on console.
To gain the benefits simply enable PHP OpCode extension in php.ini
file.
Upgrade PHP
With every release of PHP, the team has not only added new features, resolved existing bugs but they have also improved the quality of code with focus on performance improvements.
With the release of PHP 7/8, comes the Just in time Compilation
feature and upgrade to the PHP execution engine to PHP Next Gen (PHPNG
).
Using JIT, the application is compiles the generated code to native machine code during runtime. This codes runs faster and uses less memory. Whereas the PHPNG
execution engine makes improvement to the internals of the Zend Engine itself.
Cache External Data Using Memcached or Redis
Although not directly part of PHP, but adding a cache to your PHP application using Memcached or Redis with bring significant improvements to the time taken by your code to complete a given task, especially if part of the flow is to get data from external sources such a database.
Improve Existing Code
Improvements in coding style can add significant improvement in the performance of your application. Selecting a non-optimized data structure for storing a list of users can bring any application to a crawl.
So here are a few tips I would like to share.
- Data structures: Use data structures suited for a particular task. If you are going to search for a specific user in a long list, it is better to use a
Map
and not aList
. JSON
: Always useJSON
instead ofXML
as you will get better performance.- Use parametrized SQL queries. These get compiled even on the server and cached.
- Cache database responses so you have less trips to the DB server.
- Named Classes: In general use classes instead of associative arrays as they use less space and are faster to access. Only exception is when it does to deserialization and serialization where classes lose to associative arrays.
- Native functions: Always use native functions instead of writing your own.
- When using Arrays, always use functions Array functions instead of foreach loops. They are much better optimized.
- Code profiling: Use tools like Blackfire, XDebug Profiler, Tideways or NewRelic.
- Use OpenSwoole: Open Swoole is a complete async solution that has built-in support for async programming via fibers/coroutines, a range of multi-threaded I/O modules (HTTP Server, WebSockets, TaskWorkers, Process Pools) and support for popular PHP clients like PDO for MySQL, Redis and CURL. (verbatim from their website)
- Object Relation Mapping(ORM): ORM tools make programming easier when it comes to managing data. But they come with their own perils. You need to watch out how you use these tools. Although they will reduce your development time, but will slow things down a bit because of all the abstractions. Beware of options like ORM entity manager cache flushes.
- Reduce eager object loading.
The list above is only a subset of what improvements you can do in your code to make it faster. There are other options as well. Do provide your favorite tips on code process improvements you use in your own coding in the comment section below.
Hardware and Infrastructure Upgrades
We all know that throwing the latest and fastest hardware, physical or virtual, will increase the performance of any existing application without doing any additional coding. Depending on the level of upgrade this may give a significant boost to performance.
But I am sure you already knew that big iron leads to performance boost but comes with big money costs. Although this is an option, it is not what I would directly suggest. Check out my suggestions below.
Load Balancing
One of the easiest way to increase client serving capacity of your PHP web application is by using a load balancer to distribute request load among multiple PHP application servers.
Load balancing can be hardware or software based. Most times it is cheaper to start with software based solutions. Over the years I have found that hardware based load-balancing solutions are cheaper over the long term. They are easier to manage and offer higher level of scalability per dollar spent.
If you choose hardware load balancer there are great options from companies such as:
With software solutions your options go from free solutions, such as Nginx
and HAProxy to premium paid solutions. Below are some free open source loading balancing options:
There are commercial vendors providing software solutions as well, many bundling them with custom hardware as well.
Reverse Proxy (with cache)
Above you learned about load balancers which provider features identical to what a reverse proxy does.
Checkout my post on setting up Nginx as a reverse proxy and cache.
A reverse Proxy with caching features can significantly increase performance of your web application. The reverse proxy server allows the ability to avoid a round trip to the application server by serving content from its own cache. Depending on how you configured the reverse proxy, even in cases where you backend application server is not available the reverse proxy will serve content to clients with a downtime in availability.
I have actually done some tests on improving performance of WordPress hands on where I take a stock WordPress site serving 5 pages/second to 60 pages/second, Check out my step by step guide to improving WordPress performance.
Use Content Delivery Networks (CDN)
A CDN
is a geographically distributed group of servers that work together to provide fast delivery of your content, especially static assets like images, video, CSS
and JavaScript
, from a physical location closest to your site visitor.
This reduces request times of your website and improves customer experience.
Many CDNs provide additional services such as protection from Distributed Denial of Service
(DDOS) attacks.
Here is list of benefits that using a CDN will provide.
- Decrease load on your own network and application servers.
- Improve reliability of your website.
- Improve website speed and performance.
- Reduce attack surface of your website.
- Reduce packet loss and provider lower network latency as the content being served is from a physical location closer to the server.
- Save costs: As content is being served from the CDN your network bytes to distribute static asset serving will go down. Also your cost to manage a larger network with more compute nodes will go down.
- Scale effectively: A company providing CDN services has vast networks that are designed to scale. Random and planned spikes in user activity will be effectively handled by use of a CDN.
Use Public or Private Cloud
Make sure that all of your server are co-located. This will reduce the complexity of network as well as internal communication times between services.
Use services from Amazon AWS, Google Cloud or Microsoft Azure services if you are interested in exploring public cloud services.
Conclusion
A default PHP install is never the best option if you want to start building applications that scale. You small app today could be the next Instagram. Focus on best practices from the start. Always think about the best way to build an application.
I hope you found this post useful. Let me know what you think. If you have any questions please feel free to ask.