Performance Optimization

Performance Optimization: The Hidden Code Patterns That Slow Down Your Website

Your website might have a powerful server, plenty of RAM, a fast database and perfectly good hosting. Yet certain pages still take several seconds to load.

A puzzled business owner in a racing helmet presses the pedal of his blue go-kart, unaware that a heavy iron anchor is chained to its back, while a Clickative developer in the team’s navy uniform and safety glasses kneels behind it and cuts through the chain with an angle grinder, sparks flying

The instinct is often to upgrade the server, increase memory limits or throw more hardware at the problem.

Your ServerAll Healthy

  • 9% CPU
  • 22% Memory
  • 14% Database
  • 6% Network
yoursite.com/employees
  1. 101 queries for 100 employees
  2. Every row scanned
  3. 40 columns fetched, 4 shown

6,800 msand still loading

Everything checks out. The page is still slow.

But what if the server isn’t the problem?

A surprising amount of poor application performance comes from inefficient code patterns: repeatedly querying the database, loading thousands of unnecessary records, using indexes incorrectly, copying large data structures or performing calculations that could have been handled directly by MySQL.

These problems become particularly noticeable as an application grows. A page that works perfectly with 100 records might become painfully slow with 100,000. A dashboard that loads instantly for one user might struggle when dozens of users access it simultaneously.

Same Code, More Records

Page load time
  1. 100
  2. 1,000
  3. 10,000
  4. 100,000

Records in the table

  • Inefficient code patterns
  • Efficient code
The same page, the same server: what changes is how much work the code asks for.

The good news? Many of these problems can be identified and corrected without upgrading your infrastructure.

Let’s look at some of the most common performance bottlenecks in modern web applications, with practical examples from Laravel, PHP and MySQL.

01N+1 Queries

The N+1 Query Problem: When One Database Query Becomes Hundreds

One of the most common performance mistakes in Laravel applications is the N+1 query problem.

It happens when an application retrieves a collection of records and then performs another database query for each individual record.

Imagine displaying a list of 100 employees, including their assigned facilities. You might start with something like this:

EmployeeController.php101 queries
$employees = Employee::all();foreach ($employees as $employee) {    echo $employee->facility->name;}

Looks perfectly reasonable, right?

Except there’s a problem.

The initial query retrieves all 100 employees. Then, every time the code accesses $employee->facility, Eloquent may execute another database query to retrieve that employee’s facility.

Instead of one query, you could end up executing 101. And if the page displays 1,000 employees? Potentially 1,001 queries.

A flustered waiter dashes toward a table of hungry guests carrying a single plate, while beside the kitchen hatch his calm colleague pushes a trolley loaded with every plate at once
One trip per plate, or every plate in one trip.

That’s a lot of unnecessary database communication just to display a list.

The Solution: Eager Loading

Laravel provides eager loading to retrieve related records in advance.

EmployeeController.php2 queries
$employees = Employee::with('facility')->get();foreach ($employees as $employee) {    echo $employee->facility->name;}

Instead of querying the facility separately for every employee, Laravel retrieves the employees and their related facilities using a small number of queries: one for the employees and one for all of their facilities.1

Database Queries To Display The List

100 employees

  • One query per employee101
  • Eager loading2

1,000 employees

  • One query per employee1,001
  • Eager loading2
Ten times the employees, ten times the queries, unless the facilities come along in advance.

The difference can be substantial, particularly when working with multiple relationships. You can also eager load multiple relationships:

EmployeeController.php4 queries
$employees = Employee::with([    'facility',    'department',    'manager'])->get();

And if you only need the number of related records rather than the actual records themselves, use withCount():

EmployeeController.phpCounts, no records
$employees = Employee::withCount('assignments')->get();

This avoids retrieving entire collections just to count them.

The N+1 Problem Can Hide In Unexpected Places

Even when developers use eager loading, additional queries can sneak back in.

For example, loading posts with their comments does not necessarily mean that accessing the parent post from each comment will avoid another query. Laravel’s documentation specifically describes this reverse relationship scenario, along with its chaperone() method, which hands each comment its post without asking again.1

For development environments, Laravel also provides lazy-loading prevention, which can help expose accidental relationship queries before they reach production: outside production, a relationship that was never eager loaded stops the page with an error instead of quietly running another query.1

AppServiceProvider.phpDevelopment only
// In the boot() methodModel::preventLazyLoading(! $this->app->isProduction());

02Indexing

MySQL Indexing: Stop Making The Database Search Everything

Indexes are among the most powerful tools available for improving database performance.

Without a suitable index, MySQL may need to examine a large portion of a table to find the records matching a query. With an appropriate index, it can locate matching records much more efficiently.2

A smiling librarian holds up a card from the card catalogue and points straight at the glowing book she needs, while her colleague up a rolling ladder searches the shelves book by book with a flashlight
The card index goes straight to the book. Without it, every shelf gets searched.

Consider an assignments table containing several million records. A typical application query might look like this:

assignments.sqlRuns all day
SELECT *FROM assignmentsWHERE facility_id = 125AND status = 'active'ORDER BY created_at DESC;

If this query runs frequently, the relevant columns deserve attention. A suitable composite index could be:

assignments.sqlOne index, three columns
CREATE INDEX idx_assignments_facility_status_createdON assignments (facility_id, status, created_at);

Rather than creating a separate index for every column, a composite index can support the combination of conditions used by the query.

Without A Suitable Index

Every row examined, one after another, to find a handful

With The Composite Index

Straight to the matching rows, kept side by side in the index

Same table, same query: the index decides how much of it MySQL has to read.

Understanding Composite Indexes

Index column order matters.

An index on (facility_id, status, created_at) can support lookups using:

The index, read from the left
  1. facility_id
  2. status
  3. created_at
  • facility_id Uses the index
  • facility_id and status Uses the index
  • facility_id, status and created_at Uses the index
  • status alone Not the leftmost column

But it generally cannot provide the same lookup benefit for a query filtering only by status, because that column isn’t the leftmost part of the index.

This is known as the leftmost-prefix principle.3

You should design indexes around the actual queries your application executes, not simply add indexes to every column that appears in a WHERE clause.

More Indexes Aren’t Always Better

Indexes improve certain reads, but they also require storage and maintenance.

Every time a row is inserted, updated or deleted, MySQL may need to update the relevant indexes. Adding dozens of unnecessary indexes can therefore make write operations more expensive.2

The goal is to identify the indexes that support your most important query patterns.

Use EXPLAIN To See What’s Happening

Don’t guess whether an index is being used.

MySQL provides EXPLAIN to show how it intends to execute a query. With MySQL 8, EXPLAIN ANALYZE goes further by executing the query and reporting actual execution timings, row counts and other information about the execution plan.4 For example:

assignments.sqlShows the real plan
EXPLAIN ANALYZESELECT *FROM assignmentsWHERE facility_id = 125AND status = 'active';
EXPLAIN ANALYZE
  1. Table scan on assignmentsBefore the index: every row read, then filtered
  2. Index lookup on assignments using idx_assignments_facility_status_createdAfter it: straight to the rows that match
Rows examined against rows returned: the plan shows which kind of query you have.

This helps identify queries that scan too many rows, use inefficient execution plans or spend excessive time retrieving results.

03Less Data

Retrieving More Data Than You Actually Need

Another common performance problem is loading entire records when the application only needs a handful of fields. Consider:

EmployeeController.phpEvery column
$employees = Employee::all();

If the employee table contains 40 columns but the page only displays a name, email address and position, retrieving everything is unnecessary. Instead:

EmployeeController.php4 columns
$employees = Employee::select(    'id',    'name',    'email',    'position_id')->get();

Employee::all()All 40 columns, for every employee

Employee::select(...)The 4 the page needs

  • id
  • name
  • email
  • position_id
Less to send from MySQL, less for PHP to hydrate and hold on to.

This reduces the amount of data transferred from MySQL and the amount of information PHP needs to hydrate and retain. The same principle applies to relationships:

EmployeeController.phpOnly id and name
$employees = Employee::with('facility:id,name')    ->get();

Avoid Loading Huge Collections Into Memory

Imagine exporting 100,000 employee records. This approach loads the entire collection into memory:

ExportEmployees.php100,000 models at once
$employees = Employee::all();

A better approach is to process records in manageable chunks:

ExportEmployees.php500 at a time
Employee::chunk(500, function ($employees) {    foreach ($employees as $employee) {        // Process employee    }});

Memory While Exporting 100,000 Employees

Memory in use
PHP memory limit
  1. 0
  2. 50,000
  3. 100,000

Employees processed

  • All at once
  • 500 at a time
Only the current chunk is held in memory, so the export never needs room for all 100,000 at once.

Laravel also provides lazy() and lazyById() for processing larger datasets incrementally.5

This is particularly useful for exports, bulk updates, reports and scheduled maintenance tasks:

  • Exports

    Every record out to a file, a chunk at a time.

  • Bulk Updates

    Thousands of rows changed without holding them all.

  • Reports

    Large datasets summed up batch by batch.

  • Scheduled Maintenance

    Nightly clean-ups that never outgrow the server.

The objective is to process only the data currently needed instead of keeping an enormous collection of models in memory.

04Memory

Memory Copying Instead Of Reusing Existing Data

This is a less obvious performance issue, but it can become significant when applications manipulate large arrays and data structures.

PHP handles arrays using value semantics, with copy-on-write behavior internally.6 In practical terms, assigning an array to another variable doesn’t necessarily duplicate its entire contents immediately. For example:

example.phpShared, for now
$data = range(1, 1000000);$copy = $data;

PHP can initially share the underlying array storage. If one copy is subsequently modified, however, it may need to separate the data and allocate additional memory.

$copy = $data;
$data $copy 1,000,000 valuesOne array in memory

Two names, one array: nothing copied yet

$copy['status'] = 'active';
$data $copy 1,000,000 valuesThe original 1,000,001 valuesA full copy, in new memory

One change, and the arrays separate

A copy costs nothing until one side changes. Then it costs a whole array.

Consider a function that receives a large array, creates another copy and modifies only one value:

example.phpA second copy
function updateData($data){    $data['status'] = 'active';    return $data;}

If the array is large, modifying it can trigger additional memory allocation.

Sometimes this is necessary because you specifically want to preserve the original data. Other times, the application is creating copies without any real reason.

If you intend to modify the original array, you can work with it directly:

example.phpNo copy
$data['status'] = 'active';

You can also pass an array by reference when a function is explicitly intended to modify the caller’s variable:7

example.phpChanges the original
function updateData(&$data){    $data['status'] = 'active';}

References change how variables behave and can introduce unexpected side effects. Use them when you actually need shared modification, not simply because an array looks large.

There is another important distinction: assigning an object to another variable does not automatically clone the object. Both variables refer to the same object instance unless you explicitly clone it.8

$b = $a;
$a $b One objectThe same instance, never copied

A second object only when you ask for one with clone

Understanding these differences helps developers avoid unnecessary memory allocation without introducing complicated reference behavior throughout their code.

05Let MySQL Count

Performing Calculations In PHP That MySQL Could Handle

Sometimes an application retrieves thousands of records just to calculate something simple. For example:

DashboardController.phpEvery active row loaded
$assignments = Assignment::where('status', 'active')->get();$total = 0;foreach ($assignments as $assignment) {    $total += $assignment->rate;}

If all you need is the total, you’re retrieving and hydrating every matching assignment unnecessarily. Let MySQL do the calculation:

DashboardController.phpOne number back
$total = Assignment::where('status', 'active')    ->sum('rate');

Other useful database aggregation methods include:9

  • count()

    For counting records.

  • avg()

    For averages.

  • min() And max()

    For minimum and maximum values.

  • groupBy()

    For grouping results.

  • withCount()

    For relationship counts.

The database is designed to perform these operations efficiently.

This becomes especially important for dashboards and reporting pages that calculate totals across large datasets.

Instead of retrieving 50,000 records and processing them in PHP, you can often retrieve the exact summary your interface needs.

Rows Sent From MySQL To PHP For One Total

  • Load them all, add up in PHP50,000
  • Let MySQL add them up1
The same total, without 50,000 models built only to be thrown away.

06Filtering

Inefficient Filtering And Sorting

Even when a query has indexes, the way conditions are written can influence whether MySQL can use them effectively. Consider:

employees.sqlA function on every row
SELECT *FROM employeesWHERE YEAR(created_at) = 2026;

Applying a function to an indexed column can prevent a conventional index on that column from being used for a normal range lookup.10 A range-based condition is often more suitable:

employees.sqlA straight range
SELECT *FROM employeesWHERE created_at >= '2026-01-01'AND created_at < '2027-01-01';

This gives MySQL a straightforward range to search. Another common example is:

employees.sqlLeading wildcard
WHERE name LIKE '%smith%'

A conventional B-tree index generally cannot efficiently locate arbitrary matches when the search begins with a wildcard. A search that starts with the text, LIKE 'smith%', still can, since every match sits together in the index’s order.11

LIKE '%smith%'

Starts with a wildcard: every name is read

LIKE 'smith%'

Starts with the text: straight to the names that match

An index is sorted from the first letter, so it can only help a search that knows how a value begins.

For genuine full-text search requirements, MySQL provides FULLTEXT indexes, which are designed for a different type of search operation.12

The important lesson is to understand how your filtering conditions interact with your indexes.

A query can look simple in PHP while forcing MySQL to examine far more data than necessary.

07Caching

Caching: Stop Repeating Expensive Work

Some data changes frequently. Other data barely changes at all.

If an application repeatedly calculates the same dashboard statistics, retrieves the same configuration or generates the same report, performing the full operation on every request may be unnecessary.

Caching allows you to reuse previously calculated results. Laravel makes this straightforward:

DashboardController.phpReused for 300 seconds
$statistics = Cache::remember(    'dashboard.statistics',    300,    function () {        return [            'employees' => Employee::count(),            'assignments' => Assignment::count(),            'facilities' => Facility::count()        ];    });

The result is stored for five minutes and reused on subsequent requests while the cache entry remains valid.

Dashboard Requests Over Ten Minutes

Stored for 300 seconds Expired, so calculated once more
  • Calculated: three count queries
  • Read from the cache
Two calculations in ten minutes, however many people open the dashboard.

Laravel supports multiple cache backends, including Redis and Memcached.13

Caching can be particularly effective for:

  • Dashboard Statistics

    Totals and counts many people look at, all day long.

  • Configuration

    Frequently accessed settings that rarely change.

  • Navigation And Menus

    Menu structures built the same way on every page.

  • Expensive Reports

    Results that take real work to put together.

  • Reference Data

    Lists and lookups the whole application shares.

  • Repeated API Responses

    The same answer from another service, asked for again and again.

If an assignment changes, a cached assignment count may become outdated. You need a strategy for refreshing or invalidating cached data when its underlying records change.

Caching something that should always be current without handling updates can create correctness problems.

08Queues And Batches

Background Processing And Batch Operations

Not every operation needs to happen while a visitor is waiting for a page to load.

Generating large PDF reports, importing thousands of records, sending bulk notifications and processing large files can consume substantial resources.

  • Large PDF Reports

    Pages of figures, laid out and rendered.

  • Record Imports

    Thousands of rows checked and saved.

  • Bulk Notifications

    Messages to everyone on a list.

  • Large Files

    Uploads to resize, convert or read through.

Laravel queues allow these tasks to be processed separately from the main web request.14

Instead of making a user wait while a report is generated, the application can dispatch a queued job and notify the user when the result is ready.

Without A Queue

Web request The visitor waits while the PDF report is generated

With A Queue

Web request The job is dispatched and the page answers at once
Queue worker Ready The report builds in the background, then the visitor is notified
The same work, done where nobody has to sit and watch it.

Batch Operations Also Matter

For example, updating 5,000 records individually can generate thousands of separate database operations.

Database Operations To Update 5,000 Records

  • One record at a time5,000
  • One bulk update1
When every record gets the same change, one statement can do the work of thousands.

Where appropriate, bulk updates, inserts and deletes can reduce database communication substantially.5

The right approach depends on the operation, relationships, validation requirements and transaction behavior. A mass update, for example, skips the model events that saving each record one by one would fire.

09Server Config

Don’t Forget PHP And Server Configuration

Not every performance issue is caused by application code. PHP has several runtime features that can influence performance.

One particularly important example is OPcache.

OPcache stores precompiled PHP bytecode in shared memory, reducing the need to load and parse PHP scripts on every request.15

Without OPcache, Every Request

  1. Load The ScriptsEvery PHP file it needs
  2. ParseThe code read and checked
  3. CompileTurned into bytecode
  4. ExecuteThe request finally runs

With OPcache

  1. Load The ScriptsSkipped
  2. ParseSkipped
  3. Cached BytecodeStraight from shared memory
  4. ExecuteThe request runs sooner
The compiled scripts wait in shared memory, so each request skips straight to running them.

It is an important production optimization for PHP applications.

Other areas worth examining include:

  • PHP-FPM Workers

    Worker configuration and process limits.

  • Memory

    Available memory and PHP memory limits.

  • MySQL Buffer Pool

    How much of your data MySQL keeps in memory.

  • Connection Overhead

    The cost of opening database connections.

  • Disk And Storage

    Disk I/O and storage performance.

  • Network Latency

    The distance between the application and its database.

  • Logging And Debugging

    Excessive logging, or debugging left on in production.

However, configuration changes should follow actual measurements.

Increasing worker counts or memory limits without understanding the workload can simply move the bottleneck somewhere else.

10AI Review

Use AI To Find Performance Problems In Your Code

AI-assisted development has made performance auditing much more accessible.

You can provide an AI coding assistant with a Laravel controller, service class, Eloquent query or database schema and ask it to identify potential inefficiencies.

Rather than asking something vague like “make this code faster,” give it specific areas to investigate. Here are several useful prompts:

  • Find N+1 Queries

    “Review this Laravel code for potential N+1 query problems. Examine all Eloquent relationship access inside loops, nested loops and collection operations. Suggest eager loading, withCount or other appropriate alternatives.”

  • Review MySQL Indexing

    “Analyze these SQL queries and table definitions. Identify potential missing indexes, unnecessary indexes and opportunities for composite indexes. Explain the expected query patterns each index would support.”

  • Find Unnecessary Memory Allocation

    “Review this PHP code for unnecessary array copying, repeated collection transformations, excessive object creation and avoidable memory allocation. Pay particular attention to large arrays and copy-on-write behavior. Do not recommend passing everything by reference.”

  • Identify Inefficient Database Operations

    “Find opportunities to replace PHP-side calculations with SQL aggregation, reduce unnecessary database queries, select fewer columns and use batch operations where appropriate.”

  • Find Inefficient Loops And Processing Patterns

    “Examine this code for nested loops, repeated calculations, repeated lookups, redundant transformations and opportunities to reuse previously calculated results.”

  • Review The Entire Request Lifecycle

    “Trace the execution of this Laravel request from the controller through services, models and database queries. Identify operations that could cause unnecessary database access, excessive memory consumption or avoidable processing time. Prioritize findings by likely impact.”

AI can be particularly useful for spotting patterns across multiple files, but its suggestions still need to be verified. It cannot reliably determine the actual performance impact of every change without execution data, database statistics and an understanding of the production workload.

AI ReviewSpots patterns across many files

Profiling And TestingMeasures the real impact

Both
AI finds the suspects. Measurements show which ones really slow you down.

Treat AI as another tool in the optimization process, not a replacement for profiling and testing.

11Measure

Measure Before And After: Optimization Without Guesswork

One of the biggest mistakes in performance optimization is changing code simply because it looks inefficient.

Sometimes an apparently inefficient operation is perfectly acceptable. Sometimes a seemingly elegant solution creates an enormous amount of unnecessary work.

You need measurements.

Start by identifying the slowest pages, endpoints and database queries. Then examine:

  • Request Time

    Total request execution time.

  • Queries Per Request

    Number of database queries per request.

  • Slow Queries

    Slow individual queries.

  • Rows Examined vs. Returned

    Number of rows examined versus returned.

  • Memory

    Memory usage and peak memory consumption.

  • CPU

    CPU usage.

  • Response Size

    How much each response sends.

  • Concurrent Requests

    Performance under concurrent requests.

Laravel’s database query listeners can help capture query execution information.16 MySQL’s EXPLAIN ANALYZE can expose inefficient query execution.4 Profiling tools can help identify where PHP spends its time.

Make one meaningful change at a time, measure the result and compare it against the original behavior.

  1. MeasureFind the slowest pages, endpoints and queries.
  2. Change One ThingOne meaningful change at a time.
  3. Measure AgainThe same pages, the same way.
  4. CompareAgainst the original behavior.
Every change earns its place with a number, or it goes.

A page that drops from 80 database queries to 8 is an improvement worth investigating. A query that goes from 400 milliseconds to 15 milliseconds is another measurable result.

Before And After, Measured

Database queries on one page

  • Before80
  • After8

One slow query

  • Before400 ms
  • After15 ms
Results you can compare, not code that merely looks cleaner.

The goal isn’t to make the code look clever. It’s to reduce unnecessary work while preserving the application’s functionality.

12Work Smarter

Make Your Application Work Smarter, Not Harder

Performance optimization isn’t necessarily about buying a bigger server or rewriting your entire application.

Often, the biggest improvements come from identifying small inefficiencies that multiply as your application grows.

1 Unnecessary Querysmall on its own Repeated 500 Timesinside one loop 500 Wasted Queriesevery time it runs
  • An index that misses the query
  • Thousands of records for ten
  • An avoidable memory allocation
Small on their own, they add up to a noticeably slower application.

An unnecessary query repeated 500 times, an index that doesn’t match the actual query pattern, a collection containing thousands of records when only ten are needed, or an avoidable memory allocation can all contribute to a noticeably slower application.

At Clickative, we look beyond the visible symptoms. We examine how the application retrieves, processes, stores and serves information, then identify opportunities to improve performance without compromising functionality.

Whether you’re developing a new platform or maintaining an established application, the best time to address performance problems is before they become expensive bottlenecks.

The Clickative mascot sprinting with a golden stopwatch held high, giving a thumbs up

Build Smarter.
Run Faster.

Pages that drag, queries that pile up or a server that keeps needing an upgrade? Tell us about your application, and we’ll find out where the time really goes.

Explore Clickative’s web development services, from new platforms to the applications already running your business.

Make Your Projects Click.

Slow pages and heavy queries tracked down and fixed, from database indexes to caching.

References

  1. Laravel: Eloquent relationships (eager loading, counting related models, preventing lazy loading)
  2. MySQL 8.4 Reference Manual: Optimization and indexes
  3. MySQL 8.4 Reference Manual: Multiple-column indexes
  4. MySQL 8.4 Reference Manual: Optimizing queries with EXPLAIN and EXPLAIN ANALYZE
  5. Laravel: Eloquent (chunking results, lazy collections, mass updates and upserts)
  6. PHP Manual: Arrays
  7. PHP Manual: References explained
  8. PHP Manual: Objects and references
  9. Laravel: Query builder aggregates
  10. MySQL 8.4 Reference Manual: Optimizing SELECT statements and range optimization
  11. MySQL 8.4 Reference Manual: Comparison of B-tree and hash indexes
  12. MySQL 8.4 Reference Manual: Full-text search functions
  13. Laravel: Cache
  14. Laravel: Queues
  15. PHP Manual: OPcache and its configuration
  16. Laravel: Database, listening for query events