← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 12 of 24

PHP Performance Optimization

Minimizing Database Queries

Running a query inside a loop multiplies database round-trips unnecessarily; fetching everything needed in one query up front (even a slightly larger one) is almost always faster than many small ones.

Example: Minimizing Database Queries

php
<?php
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (id INTEGER, name TEXT)");
$db->exec("INSERT INTO users VALUES (1,'Alice'),(2,'Bob')");
// One query instead of querying inside a loop per user
$result = $db->query("SELECT * FROM users");
while ($row = $result->fetchArray()) {
    echo $row['name'] . "\n";
}
?>

OPcache Integration

PHP is normally interpreted fresh on every request; OPcache compiles scripts once and keeps the compiled bytecode in shared memory, skipping that repeated parsing step on every subsequent request for a major speed boost.

Example: OPcache Integration

php
<?php
echo function_exists('opcache_get_status') ? "OPcache extension loaded" : "OPcache not available";
echo "\nOPcache caches compiled bytecode, skipping re-parsing on every request";
?>

Output Buffering

Output buffering collects all generated HTML in memory before sending anything to the browser, which lets the server flush one complete response instead of many small chunks, reducing perceived network overhead.

Example: Output Buffering

php
<?php
ob_start();
echo "<p>Part one</p>";
echo "<p>Part two</p>";
$html = ob_get_clean();
echo "Buffered length: " . strlen($html);
?>

Optimizing Loops and Strings

Calling an expensive function like count() inside a loop's condition re-evaluates it on every single iteration; computing it once beforehand and storing it in a variable removes that repeated cost.

Example: Optimizing Loops and Strings

php
<?php
$items = range(1, 1000);
$count = count($items); // computed once, not on every iteration
for ($i = 0; $i < $count; $i++) {
    // work
}
echo "Loop ran $count times without recalculating count() each pass";
?>

Memory Profiling

memory_get_usage() reports how much memory your script is currently consuming, which turns vague performance concerns into concrete numbers you can track before and after an optimization.

Example: Memory Profiling

php
<?php
$before = memory_get_usage();
$data = range(1, 10000);
$after = memory_get_usage();
echo "Memory used: " . ($after - $before) . " bytes";
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.