
Getting your web application to the highest performance level is quite impossible. You need to apply different tactics at different points according to the nature of application.
PHP has faced a lot of criticism when it comes to performance benchmarking. But thanks to the contributors who gave the old language wings and introduced the latest PHP 7.x versions, which is equipped with all the necessary tools and components required for a PHP performance boost. Using PHP 7, you can build & deploy advanced apps on any hosting for PHP with such features and functionalities that could optimize its performance to higher levels.
Improve Your PHP App Speed by 300%
Cloudways offers you dedicated servers with SSD storage, custom performance, an optimized stack, and more for 300% faster load times.
In my opinion, there are a few simple tips you can use in your code for making your application perform well. Like, you can take advantage of native functions, use JSON except for XML, use caching systems, configure OPcache, PHP-FPM, Memcached properly. You can also close the DB connection and limit the DB hits.
For asset management, you can add CDNs for fast content delivery. Integrate HTTP2/SSL certificates for better security optimization and can also read various other PHP security tips here. While if you are using PHP frameworks like Laravel and Symfony, you must enable profilers in them to track what’s going wrong in code.
You Might Also Like: Tips for Laravel Performance Optimization
Enable OPcache on PHP server
OPcache is one of the building block element of PHP performance because it works directly with the code compiling process. Imagine if you are creating a request to the server and it is compiling the code every time and then sending you responses, the practice will eventually make your loading time slower. Thanks to OPcache which will cache the pre-compiled code and does not let it compile on later requests.
Conducting the PHP performance test after integrating Opcache, some experts claim that PHP performance will be 3x faster and the load time will reduce much impressively. So tracking these grounds, the importance of Opcache cannot be ignored.
OpCache is compiled by default on PHP 5.5+. However, it is disabled by default. In order to start using OpCache in PHP 5.5+, you will first have to enable it. To do this you would have to do the following.
Add the following line to your php.ini: zend_extension=/full/path/to/opcache.so (nix) zend_extension=C:\path\to\php_opcache.dll (win)
Note that when the path contains spaces, you should wrap it in quotes:
zend_extension="C:\Program Files\PHP5.5\ext\php_opcache.dll"
Also note that you will have to use the zend_extension directive instead of the “normal” extension directive because it affects the actual Zend engine (i.e. the thing that runs PHP).
Cache and Minify Static Assets
Working with PHP doesn’t mean you are working with a sole tool. Instead, you will be working with a lot of other tools by side including HTML, CSS, JS and other scripts, as they bring significant improvement in the performance of the apps. Therefore, I always recommend minifying the static scripts so that the processing time can be decreased. You do not need to do this manually every time, as you can find a lot of online tools to ease this job for you:
https://www.minifier.org/
https://javascript-minifier.com/
https://jscompress.com/
https://unminify.com/
I just minimized the HTML and CSS of my PHP website and after doing the PHP performance test here is the result of load time lowering down from 756 ms to 546 ms. It can also low down more if I will minify all the scripts.
The next thing you must apply is caching systems like Varnish for static content. Varnish can also speed up the process of PHP websites and will give you optimum performance benefits because it caches HTML. It gives you the ability to cache components for certain time and then purge it all. Custom URLs which are helpful can also be cached when you create ecommerce shops in PHP.
Configure Memcache For Database
Memcached is a distributed memory caching system. It speeds up websites having large dynamic databases by storing database object in dynamic memory. The purpose of storing in a dynamic memory is that it reduces the pressure on a server whenever an external data source requests a read. A Memcached layer reduces the number of times database requests are made. Memcached stores the values (v) with the key (k) and retrieves the values (v) with the key (k) without even parsing the database queries and stays away from all these hassles.
You can easily install Memcache by running the following Sudo command:
sudo apt-get install memcached
After then just echo phpinfo() function and see if it is running.
But if you are a Cloudways customer you don’t need to do this. All you need to do is go to the “Manage Services” section and enable it by a toggle button. Now you can start consuming Memcache in your code for caching DB queries.
Update PHP Version
Since PHP 7.x versions are launched, it is recommended by many experts to upgrade your app to PHP7.x version. While now we already have PHP 7.3 RC1 available and you can see what’s new in the version and in PHP benchmark. Contributors are working hard to optimize PHP performance in each version and introducing updates for security and better performance.
If your application is still stuck at PHP 5.6 or much lower version, update that ASAP to PHP 7.x. According to Zend resource, CMS like Magento runs 3x faster and Drupal 8 runs 75% faster. One WordPress request on PHP 5.6 executes under 100M CPU instructions, while PHP7 only executes it under 25M CPU instructions. When the PHP performance test conducted on the Laravel and Zend framework, we obtained the following results:
So this is now an established fact that you must upgrade to the newest version of PHP without breaking your application. You can get help from core contributors on GitHub also.
Improve Code for Better Process
Code improvement is another important thing for performance optimization. You must avoid writing messy code and should try to optimize it by using more native functions. Utilize JSON data types instead of XML, never repeat variable declarations, always use isset() as it is much faster.
Do not make your controllers fat and model thins, always write business logic in controllers and let models handle the DB things. Avoid redundant functions and classes and try to write a standard class and inherit it in others.
Always disable debugging options on live servers, close the DB connections and avoid writing SQL queries in loops like foreach(). Also, limit your DB hits and do not make so many requests at once.
You Might Also Like: Extensive Guide to MySQL Performance Tuning
Deploy PHP on Cloud Hosting
After completing development on dev servers, the next step is to deploy PHP apps on to the hosting servers. Hosting also plays a vital role in the speed and performance of PHP applications. If your server is powerful and highly optimized then your requests will be processed fastly.
Normally, I don’t recommend Shared hosting servers for PHP applications when you have fully functional Cloud servers like Vultr, Linode and DigitalOcean servers available for just $. Honestly, it can be a nightmare for you at any time.
Also, if you don’t know how to create LAMP/LEMP stacks on cloud servers, then don’t worry, because at Cloudways you can launch servers and applications on these servers within a few clicks. Just select custom PHP app from the dropdown and launch it.
The most important thing is that all the services which I defined above are available on single clicks and you don’t require any manual configuration of it. Whether it is, GIT, Composer, Apache, Nginx, Memcache, Opcache, Elasticsearch, Varnish cache, PHP versions, etc.



Get Ready for Core Web Vitals Update
Ebook to Speed Up Your Website Before You Start Losing Traffic.
Thank You
Your list is on it’s Way to Your Inbox.
PHP Performance Tuning Tips from the Community
In order to clarify the issue to some extent, I myself, held an interactive session on social media with the community to know what they think about PHP performance and benchmark level. I developed questions on Reddit and other hosting fora to get interesting replies from the large PHP community. Meanwhile, I received answers from known developers on Twitter too.
Here’s what different developers on Twitter had to say on this topic:
Zeev Suraski
Zeev Suraski, a known PHP developer and co-founder of Zend Technologies replied to the question emphasizing on few things, including updates for potential performance gains
Marco Pivetta
Also: avoid I/O (and its side-effects) whenever it can be avoided.
Uncle Cal
I too support Uncle Cal’s view that PHP stands as the best choice for building faster web apps. But it should not be overestimated for developing real-time sensitive applications.”
Uncle Cal gave his opinion with a contrasting view. To use some other language for real-time applications. But classified PHP as the best choice for modern fast web apps.
Mike Pearson
Another user Mike Pearson responded with some useful PHP performance tips to optimize overall app performance:
Byron Nagi
array functions were technically slower because you are invoking a function for every item in the array? I mean either of those is a micro-optimization anyway but still just curious.”
Byron Nagi replied with a question itself that indeed looked like a useful thought:
MP
Mike Pearson again replied to this question with the following answer:
Beno!t
(use $data[] = ‘foo’ ; instead of array_push(), etc) + my own pro-tip: when instantiating objects
within a big loop, use a factory which clones a prototype of the object instead of new MyObject(); (66% faster).”
Symfony enthusiast, Beno!t contributed his thoughts like a professional developer:
Pietro Iglio
Peter Iglio recommended using Swoole extension. As it helps optimizing apps speed:
Sylvestre Ho
“Use cache wherever possible in order to reduce the number of DB queries. Optimize the DB queries too, these are often the performance bottleneck of any web application regardless of the stacks/frameworks that are used.
Well, I too personally recommend this technique for reducing app’s dependence on DB queries. It is because of the fact that cache has the functionality to load app pages faster. It lessens the database communication and makes data retrieval faster.”
Sylvester Ho shared his thoughts about using Cache for reducing the load on DB queries. As these few little things work impressively for apps regardless of their infrastructure.
Vladinator
Vladinator defined his solution in a quite smart way. He proposed avoiding DB queries dependence and looping of Entity manager:
Aurora Eos Rose
In my opinion, her thought also holds the highest value. Because you just cannot optimize your app speed until you have a rightly configured web server.”
Aurora came up with a little different view. She particularly emphasized on installing and configuring PHP servers perfectly for an application:
Magento Guru (Raj)
A very well-known Magento developer, Raj replied with a remarkable tweet. He explained the usage of Varnish and Redis for app optimization:
Hassan Juniedi
-Use php-ppm for caching.”
Hassan Juniedi responded with his SQL queries and caching solutions:
Joshua Ray Copeland
Joshua expressed his views in a quite definitive manner. He explained the question in detail. He highlighted firmly on the usage of PHP 7.x and Blackfireio for optimizing apps’ speed.
Fraser Reed
sure you understand what the ORM is doing.
Apart from Twitter, I also decided to post the question on Reddit. So that I could get answers from the wider community of PHP developers. Here are some interesting replies I received from Redditors about PHP performance tuning.”
Fraser Read gave a different view about keeping a check on ORMs. He emphasized on using them precisely to avoid extra and inefficient DB queries:
mYkon123
Anywhere. If the bottleneck is found, a good solution can be found. Usually, something like caching, background-tasks, queue, reorganizing workflow, database indices, load-balancer, upscaling vertical/horizontal, outsourcing to micro-services with another language, etc.”
mYkon123 replied the question highlighting the importance of apps and their main bottlenecks. They can range on many issues, but finding and fixing them is quite essential for app performance.
AllenJB83
I too believe that handling DB queries smartly can result in better performance for apps. As it is one of the major issues different applications have in their run-time execution.”
A highly active user with major PHP threads on Reddit, AllenJB83 gave his view about Database queries. He emphasized on taking DB queries into consideration for fixing performance issues.
Firehed
Another Reddit user, Firehed proposed a little but smart solution to improve PHP performance in his answer:
BlueScreenJunky
While BlueScreenJunky explained the problem in quite a detail. As for how the ping drop between the staging server and the production DB can cause incompressible delays for every query.
Beatniak
Log what costs the most time in your application with things like https://underground.works/clockwork/ You can log that in production just for your team:if ({requestIP} === {officeIP} && Request.has( ‘debug’ )) Log.this.stuff()Improve the low hanging fruit. Most often those are database queries with non-indexed
joins. Fix those problems with tips from https://use-the-index-luke.com/Because you can see the timing cascade (like the network tab in the developer tab of Chrome) of your application, you know what the bottlenecks are. And thus, what to spend time on to make your application faster.”
Beatniak explained his answer in detail and underlined several points in his reply. He particularly highlighted the importance of checking logs for PHP performance monitoring. As it enables you to know the actual problem causing the performance issue.
twisted1919
should display some items we have for sale which would be fetched from a remote API. Since the project was super simple, we decided to not use any framework nor a database. We generally use Yii Framework which is super fast anyway. We cache the API calls and load them at need and we do the display, search, sorting,
filtering, etc just in PHP and we’re using a bit JS for UI/UX. This quickly reminded us how blazing fast things can be when there is little to no
overhead, as opposed to using a framework and connecting to a database. I know that most of the projects don’t get away with this, but this was a super simple
case where we wanted to experiment a bit. So I guess the performance tip is, one of the things you should always consider when developing is to make sure you avoid any overhead that can be avoided by
Default. Also, talking with a database is expensive. I do also second his opinion about keeping apps simple in every possible way. You should always avoid having any extra overhead of functional features. Which might not have any particular role in the application, but causes the app to slow down because of unwanted resource usage.”
twisted 1919 gave his answer in a little contrasting manner. He shared his experience of
developing a simple project and analyzing its performance:
TorbenKoehn
-Your customer requires to make them searchable by many factors
-Write SQL queries with 8 joins and GROUP BY/DISTINCT and wonder why the page takes 80 seconds to load (or your SQL server is suddenly gone)
-Learn about ElasticSearch, build an index, use it
-Have ~200ms response times for your searches
-??????
-PROFIT!!! There are three things that I constantly have to optimize regarding performance: 1. Database interaction. Use caching, memory tables/own search indexes and things like ES to solve this. 2. File system interaction. Especially related to file caching or logging. To solve this, use services like Redis for caching and log to ES. 3. Intensively mapping arrays to objects, back to arrays, back to objects, etc. To solve this, KISS. DTOs are nice for auto-completion and stability but have a lot of memory overhead with large datasets and intensive mapping through multiple loops.
Another active Redditor, TorbenKoehn made his remarks about cache issues. He said that solving cache issues helps optimizing app load time and performance.
Yewbatrom
Yewbatrom shared his experience about how he optimized his apps performance by just fixing two issues:
Garethp
Evilmaus also explained the question of taking database issues into regard. He stated how he fixed small database issues to make his app performance faster.”
This is how another Redditor Garethp responded to the question:
evilmaus
I always put foreign key constraints on my database tables. I do it primarily for data integrity, but it also makes for fast joins. I find that foreign keys are also my second most used columns for selecting from a database. I also put in unique indexes on columns that should contain unique values. Again, this is for integrity purposes but has the nice side benefit that these columns are also common for me to use in queries.
When possible, I take collections of entities and key those collections by whatever ID the entities have. That way, I can quickly look up specific ones instead of having to search through the entire collection every time I want a particular item. If I’m wanting entities by something that isn’t necessarily unique, I just group by that field instead.
I haven’t yet had a call to use them, but binary trees are rather fun in concept.
Supercharged Managed PHP Hosting – Improve Your PHP App Speed by 300%
Final Words!
These were some of the valuable inputs I have gathered from Twitter and Reddit, that defines the valuable insights of the developer community. As what they think about PHP performance tuning and what it takes to optimize it more to get the optimum benefit out of apps. So what is your opinion about this topic? Do let me know your thoughts in the comments section below.
Q. Why is PHP so fast?
PHP is much faster than other options (such as ASP) because of its faster load time as a result of its own memory space that removes most of the overhead in execution.
Q. How does PHP measure performance?
You can use a host of tools to measure the performance of PHP code. The tool options include code profilers, app performance management tools, user monitoring, and server log analyzers.
Shahroze Nawaz
Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling.