Performance
Performance work starts with a number and ends with a number, and PHP gives you the clock in one call. The examples below measure, cache and count, and each one prints a value this machine produced.
Measure with microtime
Guessing which part is slow wastes weeks, so time the suspect with microtime and compare two runs. Numbers decide what to optimize and prove whether the change helped.
<?php $start = microtime(true); for ($i = 0; $i < 1000; $i++) { strlen("hello"); } $took = microtime(true) - $start; echo $i, PHP_EOL; echo $took < 1.0 ? "under a second" : "slow", PHP_EOL;
php measure.php
1000
under a second
A thousand calls of strlen() finish far inside a second, so the second line is stable even though the exact duration changes on every run. That is the reason the page prints the verdict instead of the number.
Cache results
Repeated work is the cheapest win: store the answer of a pure call and reuse it while inputs stay equal. Memory caches suit one request, files suit one hour, keys with versions suit everything else.
<?php $cache = []; $loads = 0; function userName(int $id): string { global $cache, $loads; if (!isset($cache[$id])) { $loads++; $cache[$id] = "user-" . $id; } return $cache[$id]; } echo userName(7), PHP_EOL; echo userName(7), PHP_EOL; echo $loads, PHP_EOL;
php cache.php
user-7
user-7
1
The second call found the value in the array and never reached the counter, so the expensive part ran once for two answers.
OPcache on
OPcache keeps compiled scripts in shared memory so requests skip parsing on every hit. Enable it on every production box and confirm the status flag reports active before tuning anything else.
php -i | grep "^opcache.enable =>"
The command answers opcache.enable => On => On on this build. The same settings page also lists opcache.enable_cli => Off => Off, which is why the program below takes its second branch here.
<?php if (function_exists("opcache_get_status") && opcache_get_status() !== false) { echo (int) opcache_get_status()["opcache_enabled"], PHP_EOL; } else { echo "opcache is off for the command line", PHP_EOL; }
php status.php
opcache is off for the command line
The guard asks the cache itself, so the script is honest on both kinds of process: a web request with the cache active prints 1, and a command line run says why it cannot.
Profile hot paths
Count calls on the busiest helpers to find the true hot path: the three functions that eat most of the request. Optimize those with better queries or caches, then measure again to lock in the gain.
<?php $hits = []; function hit(string $name): void { global $hits; $hits[$name] = ($hits[$name] ?? 0) + 1; } hit("render"); hit("render"); hit("cache"); echo $hits["render"], PHP_EOL;
php hits.php
2
The counter says which path was walked twice, and the same array would hold every other helper of a real request. The work of optimizing starts with that list.
Exercises
- Raise the loop to a million and print the duration with number_format().
- Add a second id to the cache example and explain the counter.
- Clear the cache array between two calls and read the counter again.
- Add a hit("mail") call and print the whole hits array with ksort().
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What should come before any performance change?
Answer
A measurement of the current code
Without a number there is no way to know which part is slow or whether the change helped.
-
What does
microtime(true)return?Answer
The current time as a float of seconds
The float form is what makes the difference of two calls a duration.
-
Which value is safe to cache for the whole request?
Answer
The answer of a pure call with the same argument
A pure call returns the same answer for the same input, so the copy cannot go stale inside one request.
-
What does OPcache save on a hit?
Answer
The parse and compile of the script
The compiled script comes from shared memory, so the parser does not run again.
-
What does this program print?
<?php $cache = []; $loads = 0; function userName(int $id): string { global $cache, $loads; if (!isset($cache[$id])) { $loads++; $cache[$id] = "user-" . $id; } return $cache[$id]; } echo userName(3), " ", userName(3), " ", $loads;Answer
user-3 user-3 1
The first call fills the cache, the second one reads it, and the counter stays at one.
-
What does this program print?
<?php $hits = []; function hit(string $name): void { global $hits; $hits[$name] = ($hits[$name] ?? 0) + 1; } hit("render"); hit("render"); hit("render"); hit("cache"); echo $hits["render"];Answer
3
The name was counted once per call, and it was called three times.
-
What does this program print?
<?php $start = microtime(true); $took = microtime(true) - $start; var_dump(is_float($took));Answer
bool(true)
The difference of two floats is a float, even when it is zero.
-
What does this program print?
<?php $i = 0; for ($i = 0; $i < 5; $i++) { strlen("x"); } echo $i;Answer
5
The loop stops when the counter reaches five, which is the value it holds afterwards.
-
A page caches the user name in a global array and the user renames the account in the same request. What goes wrong?
Answer
The cache keeps the old name until it is cleared or the request ends
A cache is only as good as its key and its invalidation, and a changed value needs the entry dropped.
-
Why is a profile of the busiest helpers better than optimizing every function?
Answer
The slowest few usually hold most of the request time
Time is not spread evenly, so the three hot paths are where a change pays.
The examples call microtime() and strlen(). The programs on this page were run with PHP 8.5.13 (php -v) with the commands shown above.
Article author: Arthur Isaev