📊 20. Performance Optimization (PHP)

Improving PHP performance is critical for faster websites, better SEO, and lower server costs.


⚡ 1. Caching

Caching stores precomputed results so PHP doesn’t need to process the same request again.

🔹 Types of Caching:

✅ 1. Output Caching

Stores full HTML output.

ob_start();// Your PHP logic
echo "Hello World";file_put_contents("cache/page.html", ob_get_contents());
ob_end_flush();

✅ 2. File Caching

Save data in files to avoid repeated DB queries.

$cacheFile = 'cache/data.json';if (file_exists($cacheFile)) {
$data = json_decode(file_get_contents($cacheFile), true);
} else {
$data = getDataFromDatabase();
file_put_contents($cacheFile, json_encode($data));
}

✅ 3. Memory Caching (Best Performance)

Use tools like:

  • Redis
  • Memcached
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);$key = "users";if ($redis->exists($key)) {
$users = json_decode($redis->get($key), true);
} else {
$users = getUsersFromDB();
$redis->set($key, json_encode($users), 60);
}

🚀 2. OPcache

OPcache stores compiled PHP bytecode in memory, so scripts don’t need to be recompiled on every request.

🔹 Enable OPcache

In php.ini:

opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
opcache.revalidate_freq=2

🔹 Check OPcache Status

<?php
print_r(opcache_get_status());
?>

🔹 Benefits:

  • ⚡ Faster execution
  • 🔥 Reduced CPU usage
  • 📉 Lower server load

🧠 3. Code Optimization

Writing efficient PHP code is equally important.


✅ Avoid Unnecessary Loops

❌ Bad:

for ($i = 0; $i < count($arr); $i++) {

✅ Good:

$len = count($arr);
for ($i = 0; $i < $len; $i++) {

✅ Use Built-in Functions

❌ Bad:

$len = 0;
while(isset($str[$len])) $len++;

✅ Good:

$len = strlen($str);

✅ Minimize Database Queries

❌ Bad:

foreach ($users as $user) {
getUserDetails($user['id']);
}

✅ Good:

SELECT * FROM users WHERE id IN (...);

✅ Use Prepared Statements

$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);

✅ Avoid Including Files Multiple Times

require_once 'config.php';

✅ Use Proper Data Structures

  • Arrays vs Objects wisely
  • Use isset() instead of array_key_exists() when possible (faster)

✅ Turn Off Error Display in Production

display_errors = Off
log_errors = On

🔥 Pro Tips (Advanced)

  • Use Gzip Compression
ob_start("ob_gzhandler");
  • Enable HTTP caching headers
header("Cache-Control: max-age=3600");
  • Use CDN for static assets
  • Optimize images & CSS/JS

🎯 Summary

TechniqueImpact
Caching🔥 Very High
OPcache⚡ High
Code Optimization🚀 Medium