Performance
| Measure with microtime | |
| Cache results | |
| OPcache on | |
| Profile hot paths |
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.
$start = microtime(true); for ($i = 0; $i < 1000; $i++) { strlen("hello"); } $took = microtime(true) - $start; echo "took " . $took . "\n";
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.
$cache = []; function userName(int $id): string { global $cache; if (!isset($cache[$id])) { $cache[$id] = loadName($id); } return $cache[$id]; }
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
opcache.enable => On => On
$status = opcache_get_status(false); echo (int)$status["opcache_enabled"] . "\n";
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.
$hits = []; function hit(string $name): void { global $hits; $hits[$name] = ($hits[$name] ?? 0) + 1; } hit("render"); hit("render"); echo count($hits) . "\n";
Next: Deploy PHP
Article author: Arthur Isaev