PHP application performance comes down to two things: how fast your code executes, and how often it has to execute at all. The fastest code is code that does not run — which is why caching is the most powerful performance tool. This guide covers 10 practical optimizations, ordered roughly from easiest quick-wins to more involved improvements.
Table of Contents
1. Enable OPcache (If Not Already On)
OPcache is the single highest-impact PHP performance improvement available. It compiles PHP scripts to bytecode once and caches the result in memory — eliminating the parse-and-compile step on every request.
; php.ini — enable and configure OPcache:
opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=20000
opcache.validate_timestamps=0 ; Set to 1 in development for auto-reload
opcache.revalidate_freq=0
opcache.interned_strings_buffer=16
opcache.fast_shutdown=1
Most managed hosting providers (Hostinger, SiteGround, A2) enable OPcache by default. Verify it is active:
var_dump(function_exists('opcache_get_status') && opcache_get_status()['opcache_enabled']);
// Should output: bool(true)
Expected improvement: 3–10x faster PHP execution for cache hits compared to no OPcache.
2. Fix N+1 Query Problems
The N+1 problem is the most common performance issue in Laravel applications. It occurs when code runs one query to fetch a list, then one additional query per item to fetch related data.
// N+1 — 101 queries for 100 posts:
$posts = Post::all();
foreach ($posts as $post) {
echo $post->user->name; // 1 query per post
}
// Fixed with eager loading — 2 queries total:
$posts = Post::with('user')->get();
foreach ($posts as $post) {
echo $post->user->name; // No additional queries
}
Use Laravel Debugbar (development) or Laravel Telescope to identify N+1 problems in your application. Even a page that “feels fast” can be running 50+ unnecessary queries.
3. Add Database Indexes on Query Columns
-- Before adding an index, check the execution plan:
EXPLAIN SELECT * FROM posts WHERE user_id = 1 AND status = 'published';
-- If you see "type: ALL" (full table scan), you need an index.
-- Add a composite index for common query patterns:
ALTER TABLE posts ADD INDEX idx_user_status (user_id, status);
-- Now the same query uses idx_user_status — dramatically faster on large tables
In Laravel migrations:
Schema::table('posts', function (Blueprint $table) {
$table->index(['user_id', 'status']); // Composite index
$table->index('published_at'); // Single column index
});
A missing index on a 100-row table has no impact. On a 100,000-row table, it means a query that should take 1ms takes 500ms.
4. Cache Expensive Operations
// Without caching — database hit on every request:
$popularPosts = Post::where('views', '>', 1000)->latest()->take(10)->get();
// With caching — database hit once per hour:
$popularPosts = Cache::remember('popular_posts', 3600, function () {
return Post::where('views', '>', 1000)->latest()->take(10)->get();
});
// Cache with tags (allows selective invalidation):
$posts = Cache::tags(['posts', 'homepage'])->remember('homepage_posts', 3600, fn() =>
Post::published()->latest()->take(5)->get()
);
// Invalidate when a post changes:
Cache::tags(['posts'])->flush();
Use Redis for production caching — it is significantly faster than file-based caching and supports cache tags.
5. Use select() Instead of Fetching All Columns
// Fetches all columns including large text fields:
$users = User::all();
// Fetches only what you need:
$users = User::select('id', 'name', 'email')->get();
// In a list view, you rarely need the password hash, bio, settings JSON, etc.
// Fetching only necessary columns reduces memory usage and query time.
6. Optimize Laravel for Production
# Cache the configuration (eliminates config file loading on each request):
php artisan config:cache
# Cache routes (eliminates route file parsing on each request):
php artisan route:cache
# Cache views (pre-compile Blade templates):
php artisan view:cache
# Optimize class autoloading:
composer install --no-dev --optimize-autoloader
# Run all production optimizations at once:
php artisan optimize
Do not run these in development — cached config and routes do not reflect code changes until re-cached. Clear with php artisan optimize:clear.
7. Profile Slow Code with Xdebug or Laravel Telescope
# Enable Xdebug profiling (generate cachegrind files):
# Add to php.ini:
xdebug.mode=profile
xdebug.output_dir=/tmp/xdebug_profiles
xdebug.profiler_output_name=cachegrind.out.%p.%r
Open the generated cachegrind file in QCacheGrind (free) or Webgrind to visualize exactly which function calls take the most time. This is how you find the 20% of code responsible for 80% of execution time.
For Laravel specifically, install Telescope in development:
composer require laravel/telescope --dev
php artisan telescope:install
php artisan migrate
Telescope shows every query, request, job, event, and cache operation with timing data — invaluable for identifying real performance bottlenecks.
8. Use PHP 8.x JIT for CPU-Intensive Code
PHP 8.0 introduced Just-In-Time (JIT) compilation. For CPU-intensive operations (image processing, data transformation, mathematical calculations), JIT can improve performance by 50–80%. For typical I/O-bound web requests (read from database, render response), the improvement is minimal — the bottleneck is database latency, not CPU.
; php.ini — enable JIT:
opcache.jit_buffer_size=128M
opcache.jit=tracing
9. Implement HTTP Caching Headers
// For pages that change infrequently:
return response($content)
->header('Cache-Control', 'public, max-age=3600') // Cache 1 hour
->header('ETag', md5($content)); // Conditional requests
// For API responses:
return response()->json($data)
->header('Cache-Control', 'private, max-age=60'); // User-specific, 1 min
Proper HTTP cache headers allow browsers and CDNs (Cloudflare, CloudFront) to serve cached responses without hitting your PHP server at all — the most efficient possible outcome.
10. Reduce Autoloaded Classes and Middleware
// In Laravel, check how many service providers load on every request:
php artisan about // shows loaded service providers, middleware
// Defer service providers that are not needed on every request:
class AnalyticsServiceProvider extends ServiceProvider {
protected $defer = true; // Only load when Analytics class is requested
public function provides(): array {
return [Analytics::class];
}
}
Each additional middleware adds processing time. Audit your middleware stack and remove anything not needed. Global middleware (applied to every request) is the most expensive category.
Quick Performance Checklist
- [ ] OPcache enabled with
validate_timestamps=0in production - [ ] No N+1 queries — verified with Laravel Debugbar
- [ ] Indexes on all WHERE, JOIN ON, and ORDER BY columns in slow queries
- [ ] Redis caching for expensive or repeated database reads
- [ ]
select()instead ofall()where full column sets are not needed - [ ]
php artisan optimizerun before every production deploy - [ ] Cloudflare or similar CDN caching static assets and cacheable pages
- [ ] HTTP Cache-Control headers set correctly for pages and APIs
Frequently Asked Questions
What causes most PHP application slowness?
In order of frequency: slow database queries (N+1 problems, missing indexes), no caching (re-fetching the same data on every request), OPcache disabled, and fetching more data than needed (SELECT * on large tables).
Does PHP 8.3 make applications automatically faster?
Yes, marginally — PHP 8.3 is approximately 5–10% faster than PHP 8.0 on typical web workloads. But the larger gains come from query optimization and caching — a poorly optimized PHP 8.3 application will still be slower than a well-optimized PHP 7.4 application.
Conclusion
PHP performance optimization follows the 80/20 rule: fixing N+1 queries, enabling OPcache, adding database indexes, and implementing Redis caching will solve the vast majority of real-world PHP performance problems. More complex techniques (JIT tuning, bytecode analysis) have diminishing returns for typical web applications. Start with the first four items, measure the improvement with Telescope or Xdebug profiling, then tackle the next bottleneck.
Next Step for Your Project Journey
Pick your next action to keep building: download complete source code, continue with practical tutorials, or explore more project systems.

