DEV Community

Cover image for Optimizing Performance in PHP Applications
Mateus Bougleux
Mateus Bougleux

Posted on

Optimizing Performance in PHP Applications

When we are programming, regardless of the language, there are concepts and techniques we can adopt to improve both the readability and understanding of the code, as well as the performance of the application.

The biggest lesson here is: don't try to reinvent the wheel. As I always say: study and research. Most likely, someone has already faced the same problem as you and found an efficient solution. Leveraging the knowledge accumulated by the community not only saves time but also helps avoid common pitfalls and errors.

Queries and Databases

On this topic, which is very important in applications, I have already written a bit, and it's worth a read.

Optimizing Data Persistence and Reading in MySQL and Application

Performance Optimization Techniques

In addition to queries and databases, there are other fundamental areas to optimize applications. Let's highlight some:

Cache
The use of cache is essential to reduce the load on the database by temporarily storing data that is frequently accessed. The community widely uses Redis for this purpose.

Redis is an in-memory NoSQL database, highly performant but volatile, as memory is not persistent. It is ideal for cases such as:

  • Real-time consumption data
  • User sessions
  • Shopping carts

redis

Laravel abstracts the use of Redis very well, both for caching and for other purposes. However, use it with caution! Perform many tests and learn about failover techniques to handle possible unavailability. For example, if your real-time dashboard depends on Redis, what will you do if it becomes inoperative? Planning alternatives is crucial.

Code Optimizations

Some important points when talking about code optimization:

  • Loops: Not always replacing for with foreach will improve performance. Although the code may become more readable, it is essential to test using tools like Xdebug or simple functions like microtime() to validate the real impact. Pay attention to data manipulation inside the loop and avoid memory waste.

  • Native Operations: Using native PHP functions, such as array_map, is generally safer and more efficient than creating custom solutions. Remember: "No need to reinvent the wheel."

  • Minimize Loop Operations: Avoid creating unnecessary nested loops. A nested foreach can be as harmful as a SELECT *. Instead, consider alternative solutions, such as rewriting the logic or using more efficient queries to reduce complexity.

  • PSR (PHP Standards Recommendations): Adhering to PSR practices improves code readability and maintainability. Today, IDEs offer extensions that automate the application of these standards when saving changes. This not only helps in code quality but also makes life easier for those who will maintain it in the future.

  • Queues: The use of queues is becoming increasingly common. The idea is simple: if the processing of a task can be done later, remove it from the immediate execution of the method.
    Example:
    When a user makes a purchase on an e-commerce site, is it necessary to send the confirmation email instantly? Often, no. In this case, you can send the email to a queue, which will be processed in batches, saving resources and ensuring scalability.

Sub-Processes: It's not a silver bullet, but depending on the situation, it can be implemented and is worth it.
Example:
Imagine an application responsible for processing hundreds of invoices simultaneously, calculating taxes for each one. If all these operations are performed sequentially, you may face slow performance alerts, even with computational resources to spare (CPU and RAM).
In this case, subprocesses can be a solution. Divide the processing into small parts and execute them in parallel. For example, each subprocess can be responsible for calculating taxes for a group of invoices. This allows your application to make better use of available resources, speed up processing, and avoid bottlenecks.

  • Requires and Includes: Prefer the use of autoload to manage class and file loading. This not only improves performance but also avoids issues with large and unnecessary classes (the famous "megazords"). For example, loading a class with 7,000 lines just to use a method that performs a SELECT is extremely inefficient. In these situations, it is important to consider refactoring.

About the megazord, it's worth a chat about Refactoring.

Server Optimizations

data_center

The first thing you need to know is that PHP is a very lightweight language. Under normal conditions, with a machine suitable for the number of requests and with the proper code optimizations, everything tends to work well.

"But Mateus, what is a machine corresponding to the number of requests?"
I have participated in the implementation and optimization of complex applications that received more than 6 million requests per day using, on average, two machines with 2 vCPUs and 2 GB of RAM each.

Now, talking about tools:

  • PHP-FPM
    It is a FastCGI process manager for PHP, an alternative to the Apache PHP module. PHP-FPM is faster, more flexible, and widely used in production.

  • OpCache
    A caching system for PHP scripts. It stores pre-compiled PHP code in memory, allowing PHP to execute faster, reducing execution time and resource consumption.

  • Keep Versions Updated
    It is crucial to keep packages, tools, frameworks, and the PHP language as up-to-date as possible. I understand that, often, the effort to migrate from an older version, such as PHP 7.4, to a newer one, such as PHP 8.x, may seem high. However, the benefits in terms of performance, security, and support are worth the effort.

Important Considerations:
Pay special attention to the configuration of threads and child processes. Setting values too high for these configurations or allowing the use of large files can overload the machine, leading to failures and unavailability. Always adjust these configurations according to the machine's capacity and the application's actual requirements.

Monitoring

One of the most important items when talking about optimizations is understanding what needs to be optimized. For this, a good APM (Application Performance Monitoring) tool can provide valuable insights, in addition to allowing preventive actions before problems become critical.

There are several approaches to monitoring, from manually searching PHP logs to automated solutions. Among the automated tools, the following stand out:

  • New Relic
  • DataDog

These tools are known as "plug and play": just install the agent, restart the service, and configure the dashboards to create metrics and alerts.

On the other hand, there are more manual options that, although requiring more effort and knowledge from the team, may be worth it depending on the context:

  • Prometheus + Grafana
  • Elastic Stack

The challenge in using these manual tools lies in the complexity they add, especially in robust applications without a dedicated support team. These solutions require a lot of configuration, rigorous testing, and care to avoid negatively impacting performance. Additionally, they need layers and layers of failover—just one redundancy machine is often not enough.

Despite this, implementing and testing these tools can be a great challenge for a weekend!

In most cases, tools like New Relic offer a great starting point, providing significant capacity to prevent catastrophes. However, it is important to be aware of the cost, which can become significant depending on usage.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay