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

PHP Performance Optimization

Performance optimization is making your code faster and lighter, like packing a suitcase smartly so you make fewer trips. Small changes, such as asking the database fewer questions, help pages load quickly.

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
// Print `function_exists('opcache_get_status') ? "OPcache extension loaded" : "OPcache not available"` to the output
echo function_exists('opcache_get_status') ? "OPcache extension loaded" : "OPcache not available";
// Print "\nOPcache caches compiled bytecode, skipping re-parsing on every request" to the output
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
// Call `ob_start()`
ob_start();
// Print "<p>Part one</p>" to the output
echo "<p>Part one</p>";
// Print "<p>Part two</p>" to the output
echo "<p>Part two</p>";
// Declare `$html`, set to `ob_get_clean()`
$html = ob_get_clean();
// Print `"Buffered length: " . strlen($html)` to the output
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
// Declare `$before`, set to `memory_get_usage()`
$before = memory_get_usage();
// Declare `$data`, set to `range(1, 10000)`
$data = range(1, 10000);
// Declare `$after`, set to `memory_get_usage()`
$after = memory_get_usage();
// Print "Memory used: " . ($after - $before) . " bytes" to the output
echo "Memory used: " . ($after - $before) . " bytes";
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Running database queries inside a loop, which multiplies the number of queries.
  2. Leaving OPcache disabled on a production server.
  3. Optimizing code before measuring where the time is actually spent.

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.