Skip to content
Tutorials Center
My learning

Topics

Lesson 111 of 147 ยท Advanced PHP

Performance and OPcache

Make PHP fast the right way - measure with hrtime and memory_get_usage, fix common slow patterns, cache results, and configure OPcache, preloading and JIT.

PHP is fast enough for most of the web. A typical page spends far more time waiting for the database, the file system or another HTTP service than it spends running PHP code. That's good news, but it also means guessing where time goes is usually wrong. The developer who "optimizes" string concatenation while the page runs 200 SQL queries has fixed the wrong thing.

This lesson teaches the habit that actually makes programs faster: measure, find the slow part, fix it, measure again. You'll time code with hrtime(), watch memory with memory_get_usage(), learn the handful of patterns that really are slow in PHP, cache expensive results, and then look at the engine-level tools: OPcache, preloading and the JIT compiler.

You should be comfortable with functions, arrays and generators before you start.

Measure before you change anything

The most precise clock PHP gives you is hrtime(true). It returns a monotonic timestamp in nanoseconds as an integer. Monotonic means it only goes forward: unlike the wall clock, it never jumps when the server adjusts its time. Take one reading before the code and one after, and the difference is the elapsed time.

You'll also see microtime(true) in older code. It returns the current Unix time as a float in seconds. It works for rough timings, but it follows the system clock, so it can jump, and a float loses precision at the microsecond level. Prefer hrtime(true) for measuring durations.

A single measurement is noisy. The first run of a piece of code pays one-time costs (memory allocation, filling caches), and the machine is doing other things at the same time. A fair benchmark warms up first, repeats the task several times, and reports the best or the median run:

PHP A small benchmark helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Run it a few times. The numbers change on every run and will differ from anyone else's machine, which is exactly why you repeat measurements. You'll usually see implode() win, because one C function does all the work, but both finish 50,000 words in a few milliseconds. That's an important lesson too: many "slow" patterns are slow only in theory. Optimize where the measurements point.

Benchmark realistic inputs. A function that's fast for 10 items can be painfully slow for 100,000, and the reverse is also true: a clever algorithm with a big setup cost can lose on small inputs. Test with the sizes your program really sees.

Measuring memory

Memory matters as much as time. Each PHP request has a memory_limit (256 MB in our editor; often 128 MB on servers), and a script that crosses it dies with a fatal error. Two functions tell you where you stand:

  • memory_get_usage() returns the bytes PHP's memory manager currently uses for your data.
  • memory_get_peak_usage() returns the highest value reached so far in this request. The peak is the number that decides whether you hit the limit.

The classic memory win is processing data one item at a time instead of building a huge array first. A generator produces values lazily, so only one value exists at a time:

PHP Array versus generator memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both loops add up the same million numbers, 500000500000. The generator needs essentially no extra memory (0.0 MB), while the array of one million integers holds about 16 MB, because a packed PHP array stores each element in a 16-byte slot. With rows from a database or lines from a file, each element is much bigger, and the difference decides whether the script finishes at all.

Slow patterns worth knowing

Most code doesn't need tuning. But a few patterns turn fast code into slow code as data grows, and they're worth recognizing on sight.

Searching a list inside a loop

in_array() checks every element until it finds a match, so it's O(n). Calling it inside a loop over another list makes the whole thing O(n ร— m). If you look up many values, flip the list into an array whose keys are the values once, then use isset(), which is a hash lookup and takes about the same time whatever the size:

PHP in_array versus isset lookups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both approaches find the same 5,000 allowed ids. The speed-up you see will vary from run to run, but isset() is typically more than a hundred times faster here, and the gap grows with the size of the lists. The same idea fixes slow "find the matching row" code: index the rows by id first with array_column($rows, null, 'id') (see Multidimensional Arrays).

Growing an array with array_merge in a loop

array_merge() builds a brand-new array every time. Merging inside a loop copies everything collected so far on every pass, which is quadratic. Collect the pieces and merge once, or append items directly:

PHP Merging once instead of on every pass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both versions produce the same 20,000 ids (bool(true)), but the loop version copies the growing array 2,000 times and is usually hundreds of times slower. The spread operator ... is covered in Destructuring and Spread.

Other common culprits

  • Database queries in a loop. Loading a list of posts and then running one query per post for its author is the famous N+1 problem. One query with a JOIN or a WHERE id IN (...) replaces hundreds. Pagination, Search and Database Patterns shows the fix. In real applications this beats every micro-optimization combined.
  • Repeating work that doesn't change. Reading and parsing the same config file, compiling the same template or calling the same API on every request. Cache it (next section).
  • Loading everything into memory. file() on a 2 GB log, or fetchAll() on a million rows. Stream instead: fgets() line by line (Reading and Writing Files), or fetch rows one at a time.
  • Regular expressions for simple jobs. str_contains(), str_starts_with() and strtr() are clearer and faster than a regex that checks for a fixed string. PCRE caches compiled patterns, so a regex in a loop isn't a disaster, but a catastrophic pattern can be (see Regular Expressions).

Things that don't matter in modern PHP: single versus double quotes, echo with commas versus dots, count() in a for condition on a plain array (it's a constant-time read), or ++$i versus $i++. Write the clear version.

Caching expensive results

The fastest code is code that doesn't run. If a function always returns the same result for the same input and it's expensive, remember the result. This is called memoization. A static variable inside a function survives between calls (see Variable Scope), which makes it a simple per-request cache:

PHP Memoizing an expensive function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Six lookups, but only three distinct postcodes, so the slow part runs three times and the total is about 60 ms instead of 120 ms. Each "computed" line appears just before the result of the lookup that needed it. A static cache lives only for the current request, though. In a web application every request starts fresh, so caches that should last longer need a store outside PHP's memory:

  • APCu: an in-memory key-value store shared by the PHP-FPM workers on one server. Very fast, but per server and gone on restart.
  • Redis or Memcached: a separate cache server that all app servers share. The standard choice for sessions, rate limits and cached query results.
  • Files: var_export() an array into a .php file and include it; OPcache then keeps it in memory. Frameworks cache their configuration and routes this way.
  • HTTP caching: let the browser or a CDN keep the whole response (see HTTP Headers, Status Codes and Redirects). A page served from the CDN never reaches PHP at all.
PHP
// APCu: compute once per server, keep for 10 minutes
$rates = apcu_entry('exchange-rates', function (): array {
    return fetchRatesFromApi(); // slow
}, 600);

Every cache needs an answer to "when does this become stale?" A time limit (TTL) is the simplest. Deleting the entry when the underlying data changes is more precise but easier to get wrong.

OPcache: never compile the same file twice

Without help, PHP does the same work on every request: read each .php file, turn it into tokens, parse the tokens, and compile them into opcodes, the instructions the Zend Engine executes (How PHP Works walks through the pipeline). For a framework that includes hundreds of files, compiling can cost more than running.

OPcache stores the compiled opcodes in shared memory. The first request compiles a file; every later request, in every PHP-FPM worker, reuses the stored version. It's bundled with PHP and commonly gives a 2โ€“3ร— speed-up on real applications for free. In production it should always be on.

On the command line OPcache is normally off (opcache.enable_cli=0), because a CLI script usually runs once and there's nothing to reuse. Our editor runs PHP from the command line, so you can see that setting:

PHP Checking OPcache settings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The extension is loaded (bool(true)), but opcache.enable_cli is 0, so opcache_get_status() returns false and the script prints the CLI message. On a web server the same code would report how many scripts are cached, how much memory is used and the hit rate.

Typical production settings in php.ini look like this:

INI
opcache.enable=1
opcache.memory_consumption=256        ; MB of shared memory for opcodes
opcache.interned_strings_buffer=16    ; MB for shared strings
opcache.max_accelerated_files=20000   ; more than the number of .php files you deploy
opcache.validate_timestamps=0         ; never check files for changes

The last line is the important one. By default OPcache checks each file's modification time (every 2 seconds, opcache.revalidate_freq) to notice edits. In production, files only change during a deploy, so you turn the checks off and reset OPcache as part of the deploy, usually by reloading PHP-FPM. If you forget, the server keeps running the old code. Deploying PHP Applications covers this step.

Keep opcache.validate_timestamps=1 on your development machine. With it off, your edits seem to have no effect until you restart PHP, which is a confusing afternoon.

Preloading

Preloading (PHP 7.4+) goes one step further. When PHP-FPM starts, it runs a script you choose; every class and function that script loads is compiled once and stays in memory for the life of the server, already linked together. Requests can then use those classes without even the small cost of looking them up in OPcache.

INI
opcache.preload=/var/www/app/preload.php
opcache.preload_user=www-data
PHP
<?php
// preload.php: compile the framework and app classes at server start
require __DIR__ . '/vendor/autoload.php';

$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__ . '/src'));
foreach ($files as $file) {
    if ($file->getExtension() === 'php') {
        opcache_compile_file($file->getPathname());
    }
}

Preloading gives a modest gain, often a few percent, and it has a real cost: preloaded code can't change until PHP-FPM restarts, and the server must restart on every deploy. Measure before you adopt it. Many teams find OPcache alone is enough.

The JIT compiler

PHP 8.0 added a JIT (just-in-time) compiler to OPcache. Instead of interpreting opcodes, it turns hot code into native machine code while the program runs. For CPU-heavy work, such as image processing, number crunching or long-running algorithms, the JIT can make PHP several times faster.

For typical web applications the gain is small, because they mostly wait on I/O and the JIT can't speed up waiting. That's why it's off by default. Since PHP 8.4 you turn it on with a mode name (the default value is disable, which you saw above):

INI
opcache.enable=1
opcache.jit=tracing          ; compile hot code paths (the usual choice)
opcache.jit_buffer_size=64M  ; memory for generated machine code

The JIT only works when OPcache is enabled, so in our CLI-based editor it stays off. If you write a CPU-bound command-line tool, try it with php -d opcache.enable_cli=1 -d opcache.jit=tracing tool.php and compare timings with and without.

Profilers: seeing where time goes

Timing code by hand works for one function. For a whole request you want a profiler, which records every function call with its time and memory, and shows you the expensive call paths:

  • Xdebug in profile mode writes cachegrind files you open in tools like KCachegrind or PhpStorm. Great locally, too slow for production.
  • SPX is a lightweight open-source profiler with a built-in web UI.
  • Blackfire and Tideways are commercial profilers designed to run safely in production and compare runs over time.

A profile often surprises you: the slow part is a forgotten loop of queries, a logging call that writes to a slow disk, or a library doing work you didn't know about. That's the whole point of measuring.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is hrtime(true) better than microtime(true) for timing code?

    hrtime(true) is monotonic and returns an integer number of nanoseconds. microtime(true) follows the wall clock, which can be adjusted, and it's a float with limited precision.
  2. 2. You check 50,000 user ids against a list of 50,000 banned ids with in_array() inside a loop, and it's slow. What is the best fix?

    in_array() scans the whole list on each call. Flipping once makes the ids keys, and isset() on a key is a hash lookup, so the loop becomes linear instead of quadratic.
  3. 3. A production server runs with opcache.validate_timestamps=0. After you upload new code, the site still runs the old version. Why?

    With timestamp validation off, OPcache never looks at the files again. That's faster, but every deploy must reset OPcache, usually by reloading PHP-FPM.
  4. 4. Which kind of application gains the most from enabling the JIT?

    The JIT speeds up executing PHP code. Applications that mostly wait on I/O spend little time executing PHP, so they gain little; CPU-bound code gains the most.
  5. 5. What does memory_get_peak_usage() tell you?

    The peak is the maximum reached during the request. memory_limit is checked against current usage, so the peak shows how close you came to the limit.

Summary

  • Measure first: time code with hrtime(true) (nanoseconds, monotonic), warm up, repeat, and look at the best or median run. Benchmark with realistic input sizes.
  • memory_get_usage() and memory_get_peak_usage() show memory use; generators and streaming keep big data sets from filling memory.
  • Real slowdowns come from algorithms and I/O: in_array() inside loops (use array_flip() + isset()), array_merge() in loops (merge once), N+1 database queries, and loading everything into memory. Quote styles and ++$i don't matter.
  • Cache expensive results: static variables for one request, APCu, Redis or Memcached across requests, and HTTP caching for whole responses. Decide when each cache goes stale.
  • OPcache keeps compiled opcodes in shared memory; always enable it in production, set validate_timestamps=0 there, and reset it on every deploy.
  • Preloading compiles chosen classes at server start for a small extra gain; the JIT (opcache.jit=tracing) helps CPU-bound code far more than typical web pages.
  • Profilers such as Xdebug, SPX, Blackfire and Tideways show where a whole request spends its time.

Next: Command-Line PHP