PHP Performance Optimization: Advanced Techniques & Best Practices
PHP Performance Optimization: Advanced Techniques & Best Practices
Specialized Guide by Alaa Amer – Professional Web & App Developer
Application performance is crucial for success. In this comprehensive article, we'll explore advanced techniques to optimize PHP applications for maximum speed and efficiency.
2️⃣ Advanced Database Optimization
Query Optimization Class:
<?php
class DatabaseOptimizer
{
private PDO $pdo;
private array $queryLog = [];
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
$this->enableQueryLogging();
}
private function enableQueryLogging(): void
{
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Log slow queries
$this->pdo->exec("SET SESSION long_query_time = 0.1");
$this->pdo->exec("SET SESSION slow_query_log = 'ON'");
}
public function analyzeQuery(string $query): array
{
$stmt = $this->pdo->prepare("EXPLAIN ANALYZE " . $query);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function optimizedPagination(string $table, int $page, int $limit): array
{
// Use offset-free pagination for better performance
$offset = ($page - 1) * $limit;
if ($page === 1) {
$query = "SELECT * FROM {$table} ORDER BY id DESC LIMIT :limit";
$params = [':limit' => $limit];
} else {
$lastId = $this->getLastIdFromPreviousPage($table, $page - 1, $limit);
$query = "SELECT * FROM {$table} WHERE id < :last_id ORDER BY id DESC LIMIT :limit";
$params = [':last_id' => $lastId, ':limit' => $limit];
}
$stmt = $this->pdo->prepare($query);
$stmt->execute($params);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function batchInsert(string $table, array $data): bool
{
if (empty($data)) return false;
$columns = array_keys($data[0]);
$placeholders = '(' . implode(',', array_fill(0, count($columns), '?')) . ')';
$values = str_repeat($placeholders . ',', count($data));
$values = rtrim($values, ',');
$query = "INSERT INTO {$table} (" . implode(',', $columns) . ") VALUES " . $values;
$flatData = [];
foreach ($data as $row) {
foreach ($columns as $column) {
$flatData[] = $row[$column];
}
}
$stmt = $this->pdo->prepare($query);
return $stmt->execute($flatData);
}
}
Connection Pool Manager:
<?php
class ConnectionPool
{
private array $connections = [];
private array $config;
private int $maxConnections;
public function __construct(array $config, int $maxConnections = 10)
{
$this->config = $config;
$this->maxConnections = $maxConnections;
}
public function getConnection(): PDO
{
foreach ($this->connections as $key => $conn) {
if ($this->isConnectionAvailable($conn)) {
return $conn;
}
}
if (count($this->connections) < $this->maxConnections) {
$conn = $this->createConnection();
$this->connections[] = $conn;
return $conn;
}
throw new RuntimeException('Connection pool exhausted');
}
private function createConnection(): PDO
{
$dsn = "mysql:host={$this->config['host']};dbname={$this->config['database']};charset=utf8mb4";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_PERSISTENT => true,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false
];
return new PDO($dsn, $this->config['username'], $this->config['password'], $options);
}
}
4️⃣ CPU and Memory Optimization
Profiler Class:
<?php
class PerformanceProfiler
{
private float $startTime;
private int $startMemory;
private array $checkpoints = [];
public function __construct()
{
$this->startTime = microtime(true);
$this->startMemory = memory_get_usage(true);
}
public function checkpoint(string $name): void
{
$this->checkpoints[$name] = [
'time' => microtime(true),
'memory' => memory_get_usage(true),
'peak_memory' => memory_get_peak_usage(true)
];
}
public function getReport(): array
{
$currentTime = microtime(true);
$currentMemory = memory_get_usage(true);
$report = [
'total_time' => round(($currentTime - $this->startTime) * 1000, 2),
'memory_used' => $this->formatBytes($currentMemory - $this->startMemory),
'peak_memory' => $this->formatBytes(memory_get_peak_usage(true)),
'checkpoints' => []
];
$lastTime = $this->startTime;
$lastMemory = $this->startMemory;
foreach ($this->checkpoints as $name => $data) {
$report['checkpoints'][$name] = [
'elapsed_time' => round(($data['time'] - $lastTime) * 1000, 2),
'memory_delta' => $this->formatBytes($data['memory'] - $lastMemory),
'total_time' => round(($data['time'] - $this->startTime) * 1000, 2)
];
$lastTime = $data['time'];
$lastMemory = $data['memory'];
}
return $report;
}
private function formatBytes(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB'];
$power = floor(log($bytes, 1024));
return round($bytes / pow(1024, $power), 2) . ' ' . $units[$power];
}
}
// Usage
$profiler = new PerformanceProfiler();
// Some operations
$users = getUsersFromDatabase();
$profiler->checkpoint('database_query');
$processedUsers = processUsers($users);
$profiler->checkpoint('user_processing');
$report = $profiler->getReport();
error_log(json_encode($report, JSON_PRETTY_PRINT));
6️⃣ Code-Level Optimizations
Optimized String Operations:
<?php
class OptimizedStringOperations
{
// Use heredoc for large strings
public function buildLargeHTML(array $data): string
{
$html = <<<HTML
<!DOCTYPE html>
<html>
<head><title>{$data['title']}</title></head>
<body>
HTML;
foreach ($data['items'] as $item) {
$html .= "<div>{$item}</div>";
}
$html .= "</body></html>";
return $html;
}
// Use array_map instead of foreach for transformations
public function processItems(array $items): array
{
return array_map(function($item) {
return [
'id' => $item['id'],
'name' => ucfirst(trim($item['name'])),
'slug' => $this->createSlug($item['name'])
];
}, $items);
}
// Optimize regular expressions
public function validateEmails(array $emails): array
{
static $pattern = '/^[^\s@]+@[^\s@]+\.[^\s@]+$/';
return array_filter($emails, function($email) use ($pattern) {
return preg_match($pattern, $email);
});
}
private function createSlug(string $text): string
{
static $replacements = [
'/[^\w\s-]/' => '',
'/\s+/' => '-',
'/-+/' => '-'
];
$text = strtolower(trim($text));
foreach ($replacements as $pattern => $replacement) {
$text = preg_replace($pattern, $replacement, $text);
}
return trim($text, '-');
}
}
💡 Performance Optimization Checklist
- Enable OPcache in production
- Use Redis/Memcached for caching
- Optimize database queries and indexes
- Enable HTTP compression and caching
- Profile code regularly to identify bottlenecks
- Use efficient algorithms and data structures
- Minimize file I/O operations
- Implement proper error handling
Next Step
Learn about microservices architecture and load balancing for scalable applications.
📩 Need help optimizing your application performance?
Article Category
PHP Performance Optimization: Advanced Techniques & Best Practices
Complete guide to optimizing PHP application performance using caching, database optimization, and advanced techniques.
Consultation & Communication
Direct communication via WhatsApp or phone to understand your project needs precisely.
Planning & Scheduling
Creating clear work plan with specific timeline for each project phase.
Development & Coding
Building projects with latest technologies ensuring high performance and security.
Testing & Delivery
Comprehensive testing and thorough review before final project delivery.