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.
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
- 101 queries for 100 employees
- Every row scanned
- 40 columns fetched, 4 shown
6,800 msand still loading
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
- 100
- 1,000
- 10,000
- 100,000
Records in the table
- Inefficient code patterns
- Efficient code
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:
$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.
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.
$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
The difference can be substantial, particularly when working with multiple relationships. You can also eager load multiple relationships:
$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():
$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
// 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
Consider an assignments table containing several million records. A typical application query might look like this:
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:
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
Understanding Composite Indexes
Index column order matters.
An index on (facility_id, status, created_at) can support lookups using:
- facility_id
- status
- 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:
EXPLAIN ANALYZESELECT *FROM assignmentsWHERE facility_id = 125AND status = 'active';
Table scan on assignmentsBefore the index: every row read, then filteredIndex lookup on assignments using idx_assignments_facility_status_createdAfter it: straight to the rows that match
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:
$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:
$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
- position_id
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:
$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:
$employees = Employee::all();A better approach is to process records in manageable chunks:
Employee::chunk(500, function ($employees) { foreach ($employees as $employee) { // Process employee }});
Memory While Exporting 100,000 Employees
- 0
- 50,000
- 100,000
Employees processed
- All at once
- 500 at a time
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:
$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;
Two names, one array: nothing copied yet
$copy['status'] = 'active';
One change, and the arrays separate
Consider a function that receives a large array, creates another copy and modifies only one value:
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:
$data['status'] = 'active';You can also pass an array by reference when a function is explicitly intended to modify the caller’s variable:7
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 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:
$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:
$total = Assignment::where('status', 'active') ->sum('rate');
Other useful database aggregation methods include:9
count()For counting records.
avg()For averages.
min()Andmax()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
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:
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:
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:
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
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:
$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
- Calculated: three count queries
- Read from the cache
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
With A Queue
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
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
- Load The ScriptsEvery PHP file it needs
- ParseThe code read and checked
- CompileTurned into bytecode
- ExecuteThe request finally runs
With OPcache
- Load The ScriptsSkipped
- ParseSkipped
- Cached BytecodeStraight from shared memory
- ExecuteThe request runs sooner
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
BothTreat 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.
- MeasureFind the slowest pages, endpoints and queries.
- Change One ThingOne meaningful change at a time.
- Measure AgainThe same pages, the same way.
- CompareAgainst the original behavior.
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
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.
- An index that misses the query
- Thousands of records for ten
- An avoidable memory allocation
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.
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
- Laravel: Eloquent relationships (eager loading, counting related models, preventing lazy loading)
- MySQL 8.4 Reference Manual: Optimization and indexes
- MySQL 8.4 Reference Manual: Multiple-column indexes
- MySQL 8.4 Reference Manual: Optimizing queries with EXPLAIN and EXPLAIN ANALYZE
- Laravel: Eloquent (chunking results, lazy collections, mass updates and upserts)
- PHP Manual: Arrays
- PHP Manual: References explained
- PHP Manual: Objects and references
- Laravel: Query builder aggregates
- MySQL 8.4 Reference Manual: Optimizing SELECT statements and range optimization
- MySQL 8.4 Reference Manual: Comparison of B-tree and hash indexes
- MySQL 8.4 Reference Manual: Full-text search functions
- Laravel: Cache
- Laravel: Queues
- PHP Manual: OPcache and its configuration
- Laravel: Database, listening for query events