Optimising PHP Performance, why you should do it and what are common mistakes?

wait

When it comes to building high-performance web applications, optimising your PHP code is crucial. By taking steps to improve the speed and efficiency of your PHP code, you can reduce load times, improve user experience, and even save on hosting costs. In this guide, we’ll explore some tips and techniques for optimising PHP performance, specifically in the context of the popular Symfony framework.

Why bother?

While it’s true that scaling horizontally with additional webservers is a common strategy for improving web application performance, it’s still important to focus on writing well-performing code.

Lower costs

While adding more webservers can improve performance, it also increases hosting costs. Writing well-performing code can reduce the amount of resources needed to run your application, which can result in cost savings in the long run. In addition, scaling up more servers might take anywhere from a few minutes to hours depending on your setup, and this delay might result in your platform becoming unresponsive and even cause unforeseen bugs.

Higher conversion of your platform

Even with additional webservers, poorly performing code can still lead to slow load times and a subpar user experience which can greatly influence whether a user chooses to stay on your site or move on to a competitor’s site. In fact, studies have shown that even small delays in website load times can lead to a significant drop in user engagement and conversion rates.

For example, according to a report by Google, if a page takes more than 3 seconds to load, 53% of mobile users will abandon the page. Similarly, research from Akamai found that a 100-millisecond delay in website load times can reduce conversion rates by 7%.

In other words, users have a limited amount of patience when it comes to waiting for a website to load. They want to access the information they’re looking for quickly and easily, and if your site takes too long to load, they’re likely to look for alternatives.

Easier to maintain

Well-performing code is often easier to maintain and debug, making it easier to add new features and fix bugs in the future. This might not seem like a big deal when you’re first starting out, but having good coding habits will help keep technical debt low. Having a lot of technical debt will eventually clog down any development process.

Scaling horizontally can certainly help improve web application performance, it’s still important to focus on writing efficient, well-performing code. Doing so can result in cost savings, a better user experience, easier maintenance, and a reduced environmental impact.

Common mistakes

So, what are some of the common mistakes made that lead to slower performing platforms?

Making Database Queries in a Loop

A common mistake is making database queries inside a loop. This can be a major performance bottleneck, especially if the loop iterates over a large number of items. To avoid this, you can use Doctrine’s query builder to fetch all the necessary data in a single query, then use a foreach loop to process the results. For example:

// Before
foreach ($items as $item) {
    $relatedItems = $entityManager->getRepository(RelatedItem::class)->findBy(['item' => $item]);
    // do some work with $relatedItems
}

// After
$relatedItems = $entityManager->createQueryBuilder()
    ->select('ri')
    ->from(RelatedItem::class, 'ri')
    ->where('ri.item IN (:items)')
    ->setParameter('items', $items)
    ->getQuery()
    ->getResult();

foreach ($items as $item) {
    $relatedItemsForItem = array_filter($relatedItems, function ($relatedItem) use ($item) {
        return $relatedItem->getItem() === $item;
    });
    // do some work with $relatedItemsForItem
}

Not Using Prepared Statements

$username = "frank";

// Execute the SQL query
$sql = "SELECT * FROM users WHERE username = '{$username}'";
$result = $conn->query($sql);

In this example, because you’re not using a prepared statement, the database must parse and optimise the query each time it’s executed, which can be expensive for frequently executed queries.

On the other hand, here’s an example of the same query using prepared statements:

$username = "frank";

// Prepare and execute the SQL query with a prepared statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$result = $stmt->fetchAll();

In this example, we are using a prepared statement to execute the SQL query with a placeholder for the username parameter. The prepared statement is optimized by the database once and can be executed multiple times with different parameters, reducing the overhead of parsing and optimizing the statement each time it’s executed. This can improve performance and reduce the load on the database server.

Poor cache-management

Caching is an effective strategy for improving application performance, but it’s important to use it judiciously to avoid performance problems and other issues.

One potential problem with putting all data, including lists, in a cache is that it can lead to increased memory usage and potentially slower cache access times. When we cache large datasets, such as lists of items or query results, we must store them in memory, which can increase memory usage and slow down cache access times. This is particularly true if we store many large datasets in the cache.

Additionally, caching everything can lead to cache thrashing, a situation where cache resources are quickly exhausted and must be continuously replaced, leading to poor cache performance. Cache thrashing can occur when we have too many cached items, especially if those items have short TTLs (time-to-live).

We’ve seen instances in the past where not organising your cache properly can lead to big problems. For example, if your platform has categorised it’s content, it might seem easy to just cache the whole list. But if one item is updated or even removed, you have to search through all these lists to make sure your cache is up to date. This might the cache server, or even temporarily make it unavailable.

To avoid these problems, it’s important to use caching selectively and strategically. We should only cache the data that is frequently accessed or computationally expensive to generate. We should also be mindful of the size of the data we’re caching and the TTLs we set for cached items. By using caching effectively, we can improve application performance without introducing new performance problems.

Conclusion

In conclusion, writing performant code is essential for creating fast and reliable web applications. There are many common problems that can cause performance issues, including inefficient queries, unoptimized code, excessive caching, and poor use of server resources. By addressing these issues, we can create web applications that load quickly, respond promptly to user requests, and provide a better user experience.

Having a well-performing platform is critical for businesses that rely on web applications to interact with customers, partners, and employees. Slow, unresponsive web applications can negatively impact user satisfaction, leading to lost revenue and a damaged reputation. By investing in performance optimization and regularly reviewing and refining our code and architecture, we can create a fast and reliable platform that meets the needs of our users and supports our business goals.

Fuse web can help

Fuse Web has extensive experience in PHP development and architecture. Our team of experts has a deep understanding of the key strategies for building fast, stable, and scalable applications.

We can help companies with all these things by providing them with custom solutions to improve the performance and scalability of their PHP applications. Our team of experts can work closely with companies to understand their specific needs and develop a strategy that will help them achieve their goals. Whether you need help with database optimisation, caching, or load balancing, Fuse Web has the experience and expertise to help you succeed. Don’t hesitate, contact us now to see how we can help.

Related content

  1. PHP Unit Testing: A Comprehensive Guide to Ensuring Code Quality and Reliability with Codeception
    Introduction Unit testing is an essential practice for ensuring the quality and reliability of your code. In this comprehensive guide, we’ll explore how our PHP development team at Fuse Web…
  2. Excelling in Client Satisfaction: How Our PHP Development Company Harnesses Active Listening to Deliver Outstanding Results
    In the world of software development, the success of a company hinges heavily upon its ability to understand and meet the needs of its clients. As the tech industry continues…
  3. The Triumphs and Challenges of 20 Years in PHP Development: Building Scalable Websites and Lessons Learned
    Over the past 20 years, we have been at the forefront of PHP development, creating high-performance and scalable websites for clients across various industries. As we celebrate this milestone, we…
  4. Mastering PHP Performance Optimisation: A Dive into Profiling Techniques and Tools
    In this blog post, we’ll cover various techniques for optimising the performance of PHP applications, including benchmarking, profiling, opcode caching, and database optimisation. What is Benchmarking? Benchmarking is the process…
  5. Scaling PHP Applications: Strategies for Handling High Traffic and Large Data Sets
    As your PHP application grows in popularity and usage, it’s important to make sure it can handle the increased traffic and data volume. Scaling is the process of making your…
  6. Top PHP Frameworks to Watch in 2023: A Comparison of Laravel, Symfony, CodeIgniter and More
    Sometimes it might feel like there are too many PHP Frameworks to help you build your next big project in. This guide aims to help you understand the similarities and,…

Related content

  1. PHP Unit Testing: A Comprehensive Guide to Ensuring Code Quality and Reliability with Codeception
    Introduction Unit testing is an essential practice for ensuring the quality and reliability of your code. In this comprehensive guide, we’ll explore how our PHP development team at Fuse Web…
  2. Excelling in Client Satisfaction: How Our PHP Development Company Harnesses Active Listening to Deliver Outstanding Results
    In the world of software development, the success of a company hinges heavily upon its ability to understand and meet the needs of its clients. As the tech industry continues…
  3. The Triumphs and Challenges of 20 Years in PHP Development: Building Scalable Websites and Lessons Learned
    Over the past 20 years, we have been at the forefront of PHP development, creating high-performance and scalable websites for clients across various industries. As we celebrate this milestone, we…
  4. Mastering PHP Performance Optimisation: A Dive into Profiling Techniques and Tools
    In this blog post, we’ll cover various techniques for optimising the performance of PHP applications, including benchmarking, profiling, opcode caching, and database optimisation. What is Benchmarking? Benchmarking is the process…
  5. Scaling PHP Applications: Strategies for Handling High Traffic and Large Data Sets
    As your PHP application grows in popularity and usage, it’s important to make sure it can handle the increased traffic and data volume. Scaling is the process of making your…
  6. Top PHP Frameworks to Watch in 2023: A Comparison of Laravel, Symfony, CodeIgniter and More
    Sometimes it might feel like there are too many PHP Frameworks to help you build your next big project in. This guide aims to help you understand the similarities and,…