BreadcrumbHomeResourcesBlog How To Improve PHP Performance: Best Practices For PHP Apps August 17, 2023 How to Improve PHP Performance: Best Practices for PHP AppsPHP DevelopmentBy Massimiliano CavicchioliPHP performance, or PHP web app performance, is one of the most important parts of modern PHP development. From user experience and satisfaction, to scalability and server costs, ensuring your PHP application is performing its best is critical.In this blog we discuss PHP performance basics, including the basics of web app performance, why it's important, and the various metrics used in assessing performance. Then we look at performance considerations when building new applications and performance tuning tips for teams working on existing applications. Let's dive in.Table of ContentsWhat Is PHP Performance?Best Practices for PHP App Performance When Building New Applications8 PHP Performance Tuning Best PracticesFinal ThoughtsTable of Contents1 - What Is PHP Performance?2 - Best Practices for PHP App Performance When Building New Applications3 - 8 PHP Performance Tuning Best Practices4 - Final ThoughtsBack to topWhat Is PHP Performance?PHP performance refers to the efficiency in which a web application built using PHP functions in terms of speed, responsiveness, and overall resource utilization.Why Is PHP Performance Important?PHP app performance, and its associated best practices, are vital for your users to have a good experience. In a sense, PHP performance can be considered a subset of web accessibility. When looking at PHP performance, as with accessibility, you consider what device a site visitor is using to access the site and the device connection speed. Reducing the download and render time of a site improves conversion rates (rate at which site visitors perform a measured or desired action) and user retention. Ultimately, performance directly impacts this journey to a desired outcome — with improvements to performance improving conversion. For web applications, users often expect a site to load in two seconds or less. These same site visitors begin abandoning slow sites at 3 seconds — and site speed is just one factor that can impact your outcomes. If the site is slow to react to user interaction, or appears broken, this can cause users to lose interest and trust, ultimately leaving the site or web app for good.8 Key Web Application Performance MetricsSo how can teams measure PHP web app performance? There are a variety of well established metrics that teams can use to measure overall web app performance, including:MetricDescriptionUser SatisfactionUses a mathematical formula to determine overall user satisfaction. Also commonly called an "Apdex" score.Time to First ByteMeasures the time it takes to render the application on end-user devices.Time to First PaintMeasures how long it takes for the initial pixels to show on the screen.Speed IndexChecks how readily the above-the-fold content appears on a screen.Time to InteractMeasures how much time passes before a web page is fully interactive.DNS Lookup TimeMeasures the time it takes for a domain lookup to occur while the browser loads the page.Error RateTracks the percentage of request issues you incur in relation to the overall number of requests.Peak Response TimeMeasures the longest response time for a total number of requests that travel across the server.Back to topBest Practices for PHP App Performance When Building New ApplicationsWith the above factors in mind, it may seem daunting to develop a functional app with excellent PHP performance. The good news is that this is something that is top of mind for nearly every web app developer working today, so you'll have plenty of information to go off of. For teams just getting started on building a new application, these 5 PHP performance best practices are worth considering:1. Optimize Your CodeOne of the most-commonly overlooked ways to improve your PHP performance is in optimizing your web application code.Here are some suggestions to help you with the task:Choose a performant PHP framework natively supporting highly performant architectures, possibly based on the Middleware pattern instead of the MVC one (Laminas, Mezzio, Laravel 10.x, Symfony 6.x, etc...)Code your application to be stateless (no session mechanism active)Prevent the application from running out of memoryAvoid running queries in a loop; use native, optimized, SQL queries insteadUnderstand how the Swoole library works (OpenSwoole, Swoole), integrate it properly in your Web application (all the frameworks cited above support it) and the gain can be 10 fold2. Transition to HTTP/2 for supporting HTTP requestsOne of the easiest ways to architect for PHP performance when developing a new application is to use the updated Hypertext Transfer Protocol (HTTP) HTTP/2.Compared to HTTP/1.x, HTTP/2 is a more powerful and offers better overall web application performance. HTTP/2 offers the following key advantages over HTTP/1.x:It reduces latency by enabling multiplexing of requests and responsesHTTP/2 compresses the HTTP header fields effectively, which reduces overheadsIt allows request prioritizationHTTP/2 includes more protocol enhancements for better performance 3. Cache, Cache, CacheCaching is an important aspect of improving PHP app performance. At a basic level, caching involves hosting a version of files in a temporary storage location to reduce latency and bandwidth consumption. This in turn can improve overall PHP performance and user experience.When developing your caching strategy, be sure to evaluate the following caching techniques:Network caching (usually applicable on network devices like LBs, Routers, Switches, etc...)HTTP caching (the HTTP cache stores a response associated with a request and reuses the stored response for subsequent request)Reverse proxy server caching (acting as a surrogate, the proxy server intercepts user requests arriving from the Internet, forwards them to the appropriate content host, caches the returned data for re-use, and delivers that data to the requesting user)Database caching (improves scalability by distributing query workload from backend to multiple cheap front-end systems - possibly in-memory - enanching the flexibility in the processing of the proprietary data)The best part of caching is that it’s minimally invasive to implement and by doing so, your application performance — in terms of both both speed and scalability — can be dramatically improved.4. Focus on Mobile Devices First, Desktop SecondDo you try to optimize your website for desktop first, and then look at the mobile user experience? Optimizing the user experience including the performance for mobile devices is harder.Focus on mobile devices first. Remove common performance bottlenecks and test the site on mobile devices. You can then easily optimize it for the desktop afterward.5. Ensure Your Front-End Is OptimizedWeb browsers use HTTPS (secure hypertext transfer protocol) requests to fetch parts of the webpage from the web server — including things like images, stylesheets, scripts, etc.. Depending on the needs of the site, you may have a lot of large graphic files you need to load. But incorrectly handling those large graphic files can make your website load slowly.Regardless of the file type, how and when it's loaded can impact the overall page loading speed. For images, that may mean choosing the appropriate resolution for different devises, or, or even changing the file size or type being served in given situations. A few examples to consider when optimizing your web front-end include:“Minifying” the size of files (e.g. JavaScript and CSS files) by removing or shortening symbols.Combine different JavaScript and CSS files into a single bundle.If necessary, create different bundles by following the above process.Implement the asynchronous loading of JavaScript. This involves the browser parsing the webpage even when the JavaScript is being loaded.Use a Content Delivery Network for static content: when users access your site from around the world, a CDN can decrease the time it takes to serve your page to those users.Back to top8 PHP Performance Tuning Best PracticesYou can make key software engineering decisions for better web application performance, and using the right tools is the most important of them. As briefly stated above, choosing the right development framework is a great beginning to create the necessary architectural convergence centered on PHP performance.The next fundamental step is the choice of a PHP monitoring tool capable of delivering the best actionable data helping engineers to identify the problematic part of the code and web interactions, in order to satisfy the important metrics we specified above. It's also important to note that web application PHP performance tuning isn’t a one-time activity. You need to monitor the key metrics routinely and take appropriate steps in every release.For teams looking to improve performance on existing applications, here are a few best practices to consider:1. Profile Your CodeIn software engineering, 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 the frequency and duration of function calls. Most commonly, profiling information serves to aid program optimization, and more specifically, performance engineering. Profiling is achieved by instrumenting either the program source code or its binary executable form using a tool called a profiler (or code profiler). Profilers may use a number of different techniques, such as event-based, statistical, instrumented, and simulation methods.Schedule a Custom ZendHQ Demo for Your TeamReady to see how ZendHQ can help your team improve PHP app performance? Schedule a custom demo via the link below.SCHEDULE YOUR ZENDHQ DEMO 2. Refactor Your CodeOnce code bottlenecks are identified via monitoring and/or profiling tools, developers must refactor the code to eliminate those issues.. One common use case for code refactoring is in the optimization of DB queries. TTFB and overall DB queries can always be optimized, improving the TTFB and the overall scalability of the system.While writing the code (before it is analyzed by APM tools) make sure to avoid as much as possible the use of loops especially when associated with DB queries. When code loops are necessary, make good use of features like generators, coroutines or async processing in order to minimize memory footprint, speed, and, ultimately, user experience.3. Evaluate and Optimize Your Caching StrategiesA good code monitoring tool will help engineers understand cache ‘hit and miss’ and performance gains for the caching strategies applied at the code level like DB queries caching, data caching, and page caching.Iteratively, misses must be reduced to zero and more code sections must be added to the various caching buckets in a continuous effort to deliver the best PHP performances at first commit.4. Inspect and Optimize Your Server ConfigurationAnother aspect a valuable monitoring tool can help with is allowing engineers to understand how server configurations can be enhanced for improved performances.Usage of memory, access to the filesystem, DB queries connections and overall timings, etc., once properly presented, can give all the necessary hints on how to tweak the servers' configurations both at the PHP level and the web server level.A good APM will deliver sufficient data for engineers to effectively optimize connection pools configurations, memory limits, persistent connections, TCP configurations, SSL terminations and more.5. Write Clean CodeWhen coding, it is good practice to write it so that you can understand it when you simply read it on a printed page or on a screen, without having to refer to anything else. If the code is simple and concise, both the programmer and the compiler can understand it easily. Code that is easy for the compiler to understand is also easy for it to optimize for improved PHP performance.6. Use the Right Data TypesUse the right data types; data types are the key to optimizing code performance. By using the right data types, you can minimize the number of conversions that take place and make your code more efficient. In general, you should use the smallest data type that can accurately represent the data you are working with.7. Avoid Unnecessary I/OAvoid unnecessary I/O, making sure that your code only reads from and writes to the filesystem when it absolutely needs to (possibly in async/deferred jobs).8. Use the Latest PHP Version Whenever PossibleIf possible, always use the latest PHP versions. Taking this approach usually guarantees the best overall performance for PHP applications. As an example, PHP 8 introduced the JIT compiler, then followed up with additional performance improvements in PHP 8.1 and PHP 8.2.Back to topFinal ThoughtsFrom hosting costs to user experience, PHP performance can ultimately mean success or failure for many web applications. While we've outlined a number of ways to improve PHP performance here, it's ultimately just a starting point. Constantly assessing and improving your PHP performance — including finding ways to improve your optimization efforts — needs to be a priority.If you're not sure where to start, or you've inherited a nightmare application and need help, Zend offers a variety of products and professional services that can get you on the right track.Access Continuous PHP Performance Monitoring From ZendZend Admin as a Service provides continuous performance monitoring, personalized performance tuning recommendations, and prompt alerts for performance disruptions - all from one easy-to-navigate dashboard.Discover Admin as a Service Contact Us With QuestionsAdditional ResourcesBlog - Changes to Watch in PHP 8.3Blog - Why Good PHP Monitoring MattersBlog - Cloud Orchestration Basics for PHP AppsBlog - Exploring ZendHQ Role-Based Authentication FeaturesResource Collection - PHP Versions: Performance, Security, and Feature ComparisonsOn-Demand Webinar - How Queueing Enables PHP at ScaleWhite Paper - Planning Your Next PHP MigrationBack to top
Massimiliano Cavicchioli Software Architect Massimiliano Cavicchioli is a Software Architect at Zend. He has over 20 years of experience in the tech world, 16 of which he spent contributing to the PHP ecosystem at Zend. During his many years of providing consultation to enterprise corporations, Massi has developed a wealth of tangible knowledge — making him highly capable in helping companies achieve best practices in both PHP and OSS.