Php Performance
title: PHP Performance — Complete Guide to Optimizing PHP Applications description: 'Learn PHP performance optimization: opcode caching, database query tuning, autoloading, profiling with Xdebug, Redis caching, and PHP-FPM configuration.' date: 2026-06-28 lastmod: 2026-06-28 weight: 43 tags: [backend, php]
PHP performance optimization improves application speed through opcode caching, database query optimization, proper autoloading, profiling, and server configuration tuning.
## What You'll Learn
By the end of this tutorial, you'll configure OPcache, identify bottlenecks with Xdebug profiling, optimize database queries, implement Redis caching, tune PHP-FPM, and use Composer autoloader optimization.
## Real-World Use
A Laravel e-commerce site reduced page load from 1.2s to 200ms by enabling OPcache, adding Redis for session/cache, optimizing N+1 queries, and tuning PHP-FPM pool settings.
## Performance Learning Path
```mermaid
flowchart LR
A[Testing] --> B[Security]
B --> C[Performance]
C --> D[Docker/Deploy]
D --> E[Project]
C --> F{You Are Here}
style F fill:#f90,color:#fff
OPcache Configuration
; php.ini
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=20000
opcache.revalidate_freq=2
opcache.fast_shutdown=1
opcache.enable_cli=1
# Verify OPcache status
php -r "print_r(opcache_get_status());"
# Clear cache
php -r "opcache_reset();"
Composer Autoloader Optimization
composer dump-autoload -o # Classmap optimization
composer dump-autoload -a # Authoritative classmap (no filesystem checks)
{
"autoload": {
"classmap": ["src/"],
"files": ["src/helpers.php"],
"exclude-from-classmap": ["src/Tests/"]
}
}
Database Query Optimization
<?php
// N+1 problem: BAD
$orders = $db->query("SELECT * FROM orders")->fetchAll();
foreach ($orders as $order) {
$items = $db->query("SELECT * FROM items WHERE order_id = " . $order["id"]);
// N queries for N orders
}
// Eager loading: GOOD
$orders = $db->query("
SELECT o.*, i.* FROM orders o
JOIN items i ON i.order_id = o.id
")->fetchAll();
// Indexing
$db->exec("CREATE INDEX idx_orders_user_id ON orders(user_id)");
$db->exec("CREATE INDEX idx_orders_created_at ON orders(created_at)");
Redis Caching
<?php
// Install: composer require predis/predis
$redis = new Predis\Client(["scheme" => "tcp", "host" => "127.0.0.1", "port" => 6379]);
// Cache expensive queries
function getCachedUsers(PDO $db, Predis\Client $redis): array {
$cacheKey = "users:all";
$cached = $redis->get($cacheKey);
if ($cached) {
return json_decode($cached, true);
}
$users = $db->query("SELECT * FROM users")->fetchAll();
$redis->setex($cacheKey, 3600, json_encode($users));
return $users;
}
PHP-FPM Tuning
; www.conf
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
# Monitor PHP-FPM status
curl http://localhost/status?html
# Check memory usage
ps aux | grep php-fpm
Profiling with Xdebug
<?php
// php.ini
xdebug.mode = profile
xdebug.output_dir = /tmp/profiling
// Analyze with cachegrind or Qcachegrind
// Profile a specific request
xdebug_start_trace();
// ... code to profile ...
xdebug_stop_trace();
Common Mistakes
1. Not Enabling OPcache
Without OPcache, PHP compiles scripts on every request. Enable OPcache in production for 2-3x performance improvement.
2. N+1 Queries
Looping and executing a query per iteration kills performance. Use JOINs or eager loading.
3. Not Using Indexes
Full table scans on large tables are slow. Add indexes on columns used in WHERE, JOIN, and ORDER BY.
4. Loading Unnecessary Classes
Composer autoloader scans filesystem without optimization. Use classmap or authoritative autoloading.
5. Sessions on Disk
File-based sessions are slow for high traffic. Use Redis or Memcached for session storage.
Practice Questions
1. What is OPcache and why is it important?
OPcache stores compiled PHP bytecode in shared memory, eliminating the need to recompile on each request.
2. How do you identify slow database queries?
Enable MySQL slow query log, use EXPLAIN to analyze queries, or use Laravel Debugbar/Clockwork.
3. What is the difference between classmap and PSR-4 autoloading?
Classmap maps class-to-file in an array (fast). PSR-4 uses namespace-to-directory mapping (flexible but slower).
4. How do you benchmark PHP code?
Use microtime(true) before and after, or use Xdebug profiling to generate cachegrind files.
5. Challenge: Benchmark a function and optimize a slow database query with caching.
<?php
function benchmark(callable $fn): float {
$start = microtime(true);
$fn();
return (microtime(true) - $start) * 1000;
}
// Slow: direct query every time
$time1 = benchmark(function() use ($db) {
return $db->query("SELECT * FROM orders")->fetchAll();
});
// Fast: cached with Redis
$redis = new Predis\Client();
$time2 = benchmark(function() use ($db, $redis) {
$cached = $redis->get("orders:all");
if (!$cached) {
$data = $db->query("SELECT * FROM orders")->fetchAll();
$redis->setex("orders:all", 300, json_encode($data));
}
});
echo "Without cache: " . round($time1, 2) . "ms\n";
echo "With cache: " . round($time2, 2) . "ms\n";
FAQ
Mini Project: Performance Optimization Checklist
Create an optimization script that checks and reports PHP configuration.
<?php
echo "OPcache: " . (opcache_get_status()["opcache_enabled"] ? "Enabled" : "Disabled") . "\n";
echo "Memory Limit: " . ini_get("memory_limit") . "\n";
echo "Max Execution Time: " . ini_get("max_execution_time") . "s\n";
echo "Upload Max Size: " . ini_get("upload_max_filesize") . "\n";
echo "Post Max Size: " . ini_get("post_max_size") . "\n";
echo "PHP-FPM PM: " . (php_sapi_name() === "fpm-fcgi" ? "FPM" : php_sapi_name()) . "\n";
// Recommendations
if (!opcache_get_status()["opcache_enabled"]) echo "WARNING: OPcache is disabled\n";
if (ini_get("memory_limit") < "128M") echo "WARNING: Memory limit too low (<128M)\n";
What's Next
PHP Docker Deployment PHP Project
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro