PHP Performance Optimization
In this page:
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
$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";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
echo function_exists('opcache_get_status') ? "OPcache extension loaded" : "OPcache not available";
echo "\nOPcache caches compiled bytecode, skipping re-parsing on every request";
?>
Login to try C/C++/Java/PHP code in the editor
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
ob_start();
echo "<p>Part one</p>";
echo "<p>Part two</p>";
$html = ob_get_clean();
echo "Buffered length: " . strlen($html);
?>
Login to try C/C++/Java/PHP code in the editor
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
$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";
?>
Login to try C/C++/Java/PHP code in the editor
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
$before = memory_get_usage();
$data = range(1, 10000);
$after = memory_get_usage();
echo "Memory used: " . ($after - $before) . " bytes";
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 24 topics to unlock
0/24 topics done
Complete these topics first:
- PHP Date & Time
- PHP Math Functions
- PHP JSON Handling
- PHP XML Handling
- PHP cURL Introduction
- PHP REST API Basics
- PHP Composer & Packages
- PHP Autoloading
- PHP Design Patterns
- PHP MVC Architecture
- PHP Security Best Practices
- PHP Performance Optimization
- PHP 8 New Features
- PHP Type Declarations
- PHP Match Expression Advanced
- PHP Fibers
- PHP Attributes
- PHP Magic Constants
- PHP Include & Require
- PHP Iterables
- PHP SimpleXML Parser
- PHP SimpleXML Get
- PHP XML Expat Parser
- PHP DOM Parser