Internals7 min read

OPcache's cache is not the part that made it faster

The same function ran at 21.4 ns with no OPcache, 21.6 with OPcache and the optimizer off, and 14.8 with it on. What the passes removed, dumped one at a time.

Alden PikeBackend engineer and technical writer

One function, three configurations, five million calls each:

OPcache off                                21.395 ns per call  (20.865-21.869)
OPcache on, optimization_level=0           21.640 ns per call  (20.976-21.918)
OPcache on, default optimization level     14.783 ns per call  (14.362-21.648)

Medians of fifteen runs, with the full range beside each. The third row’s range reaches the other two, because one run in fifteen behaved as though the optimizer had not run; the medians are cleanly separated and that outlier is reported rather than trimmed.

The first two are the same number. Caching the compiled opcodes did nothing for run time; it saved the compilation that produced them. The 32% came from the other thing OPcache does, which has sixteen numbered passes and a debug flag that prints the op array after any one of them.

How these numbers were taken

PHP 8.5.10, NTS, arm64, Homebrew build, on an Apple M4 Pro laptop with 24 GB and 12 logical cores, running macOS and not quiesced. The JIT is off throughout. OPcache’s state and optimization level are stated with every measurement because they are the variables under test.

Timings are the median of 15 interleaved runs with three warmup rounds discarded, taken with hrtime() inside the process over 5,000,000 calls, divided by the call count, with the range given. Read them relative to each other, for the reasons the method post sets out.

Dumps come from opcache.opt_debug_level and from phpdbg -p, produced as the first post in this series describes.

Sixteen passes, and the flag that stops between them

The pass list is in Zend/Optimizer/zend_optimizer.h — not under ext/opcache, which is where most writing about it still points:

#define ZEND_OPTIMIZER_PASS_1		(1<<0)   /* Simple local optimizations   */
#define ZEND_OPTIMIZER_PASS_3		(1<<2)   /* Jump optimization            */
#define ZEND_OPTIMIZER_PASS_4		(1<<3)   /* INIT_FCALL_BY_NAME -> DO_FCALL */
#define ZEND_OPTIMIZER_PASS_5		(1<<4)   /* CFG based optimization       */
#define ZEND_OPTIMIZER_PASS_6		(1<<5)   /* DFA based optimization       */
#define ZEND_OPTIMIZER_PASS_7		(1<<6)   /* CALL GRAPH optimization      */
#define ZEND_OPTIMIZER_PASS_8		(1<<7)   /* SCCP (constant propagation)  */
#define ZEND_OPTIMIZER_PASS_9		(1<<8)   /* TMP VAR usage                */
#define ZEND_OPTIMIZER_PASS_10		(1<<9)   /* NOP removal                 */
#define ZEND_OPTIMIZER_PASS_11		(1<<10)  /* Merge equal constants       */
#define ZEND_OPTIMIZER_PASS_13		(1<<12)  /* Remove unused variables     */
#define ZEND_OPTIMIZER_PASS_14		(1<<13)  /* DCE (dead code elimination) */
#define ZEND_OPTIMIZER_PASS_16		(1<<15)  /* Inline functions */

#define DEFAULT_OPTIMIZATION_LEVEL  "0x7FFEBFFF"

The useful part is that opcache.opt_debug_level takes the same bit values. Set it to a pass’s bit and the op array is printed after that pass has run, so the difference between two dumps is exactly what one pass did. Note the off-by-one that will otherwise waste an hour: pass 5’s bit is 1<<4, so 0x10 means “after pass 5”.

Watching a function shrink

The subject is deliberately ordinary — a shipping calculation with a disabled feature flag and a couple of named constants:

<?php

declare(strict_types=1);

function shippingFor(int $weight): int
{
    $free = false;
    $base = 500;
    $perKilo = 2 * 60;

    if ($free) {
        return 0;
    }

    $total = $base + ($weight * $perKilo);

    return $total;
}

Before the optimizer, thirteen instructions:

0000 CV0($weight) = RECV 1
0001 ASSIGN CV1($free) bool(false)
0002 ASSIGN CV2($base) int(500)
0003 ASSIGN CV3($perKilo) int(120)
0004 JMPZ CV1($free) 0006
0005 RETURN int(0)
0006 T8 = MUL CV0($weight) CV3($perKilo)
0007 T9 = ADD CV2($base) T8
0008 ASSIGN CV4($total) T9
0009 VERIFY_RETURN_TYPE CV4($total)
0010 RETURN CV4($total)
0011 VERIFY_RETURN_TYPE
0012 RETURN null

2 * 60 is already int(120) on line 0003. Hold that thought.

After pass 1, simple local optimizations, the listing is unchanged. After pass 5, the control-flow pass, it is eleven — the two unreachable instructions at the end are gone, because a CFG makes unreachability a property you can compute rather than notice.

0x40000 prints the same thing again with the basic blocks marked, which is where “unreachable” stops being a judgement and becomes a label:

BB0:
     ; start lines=[0-4]
     ; to=(BB2, BB1)
...
BB3:
     ; unreachable lines=[11-12]
0011 VERIFY_RETURN_TYPE
0012 RETURN null

Four blocks, and one of them has no edge pointing at it. Nothing about that requires understanding the code — a block with no predecessors cannot execute, so it can go, and the same graph is what the later passes use to reason about which values reach which instructions.

After pass 8, SCCP, it is five:

0000 CV0($weight) = RECV 1
0001 T5 = MUL CV0($weight) int(120)
0002 CV4($total) = ADD int(500) T5
0003 VERIFY_RETURN_TYPE CV4($total)
0004 RETURN CV4($total)

Three assignments, a branch and a return have disappeared. Sparse conditional constant propagation worked out that $free is always false, so the if can never be taken and neither the branch nor its body needs to exist; that $base and $perKilo are constants, so their values can be written into the instructions that used them; and that once nothing reads those variables, the assignments that created them are dead.

The remaining passes tidy: the final listing after the whole optimizer is the same five instructions with the slots renumbered, T5 becoming T2 and CV4 becoming CV1, because thirteen instructions’ worth of variables no longer need thirteen instructions’ worth of slots.

The pass that eats microbenchmarks is not a pass

The benchmarking post opened on an experiment that measured nothing: ten million iterations of $result = 2 ** 16; timed at 18.92 ms, against 55.63 ms when the base arrived through $argv. It said the compiler folded the expression. It did not show where, and the natural assumption is that OPcache did it.

OPcache did not. phpdbg prints what the compiler emitted, before any pass runs at all:

phpdbg -pfolded pow.php

L0003 0004 ASSIGN CV1($r) int(65536)

There is no POW in that program at any stage. The fold happened while the function was being compiled, which is why the folded variant measured the same whether OPcache was on or off, and why no optimizer pass can be shown to have eaten it.

The same thing is visible in the shipping function’s first listing: 2 * 60 arrives as int(120) before the optimizer has run.

Which makes the distinction the useful one

Two literals in one expression fold in the compiler. A constant that passes through a variable does not:

$base = 500;                 // survives compilation
$total = $base + ...;        // still reads CV2($base) before the optimizer

Everything that removed those variables was pass 8, and pass 8 runs only when OPcache does. So the difference between the first two rows of the opening table and the third is not a difference in caching — it is whether a whole class of simplification happened at all.

This is the same shape the previous post in this series found for type declarations: the engine has a faster path, and the thing that unlocks it runs inside OPcache. Which is why a benchmark of either, run in a CLI with OPcache off, measures a build nobody deploys.

Where it stops, and why that is per-value

The optimizer’s reach is not a property of the function. Change one line so that the flag arrives from an array the optimizer cannot see into, and the same function keeps its branch:

function shippingOpaque(int $weight, array $config): int
{
    $free = $config['free'];
    $base = 500;
    $perKilo = 2 * 60;

    if ($free) {
        return 0;
    }

    return $base + ($weight * $perKilo);
}
0000 CV0($weight) = RECV 1
0001 CV1($config) = RECV 2
0002 CV2($free) = FETCH_DIM_R CV1($config) string("free")
0003 JMPZ CV2($free) 0005
0004 RETURN int(0)
0005 T4 = MUL CV0($weight) int(120)
0006 T3 = ADD int(500) T4
0007 VERIFY_RETURN_TYPE T3
0008 RETURN T3

Nine instructions rather than five. The branch and the fetch that feeds it survive, because nothing at compile time can say what $config['free'] holds. But $base and $perKilo are still folded into the arithmetic and their assignments are still gone: propagation stopped at the one value it could not follow and continued for the others.

That is the shape to expect in real code. Configuration read at run time keeps its branches; constants written in the file do not survive as variables.

What the DFA pass leaves behind

Dumping after pass 14 shows something the other listings do not — the SSA form the later passes work on:

shippingFor:
     ; (lines=11, args=1, vars=5, tmps=6, ssa_vars=13, no_loops)
     ; (after dce pass)
     ; return  [long]
     ; #0.CV0($weight) NOVAL [undef]
     ; #1.CV1($free) [undef]
     ; #2.CV2($base) [undef]

Every variable is numbered per assignment, the function’s return is annotated [long], and the operands carry inferred types and ranges. That annotation is not decoration: it is the input to the handler selection the previous post measured, and it is why declaring int on a parameter changes which C function runs.

no_loops in the header is the sort of fact the later passes act on. A function with loops gets a different treatment, and that is where the ranges — [long] RANGE[MIN..MAX] on a variable the optimizer could not bound — start to matter.

What it costs to run

The optimizer is work, and it happens once per file per cache warm. Compiling a 44 KB file with 400 functions, timed inside the process with opcache_compile_file():

Compile time
optimization_level=0 0.796 ms (0.776–0.820)
Default level 1.320 ms (1.273–1.375)

Sixty-six per cent more compilation, or 0.524 ms for this file, paid on the first request that touches it and on the first request after every deploy. Against 32% off every call afterwards, that is not a trade anybody needs to think about for a long-lived process — but it is a real number for the request that arrives while the cache is cold, and it scales with the size of the codebase rather than with traffic.

What to do with this

Turn the optimizer off to find out what it was doing for you. opcache.optimization_level=0 with OPcache still enabled isolates it cleanly, and the difference between that and the default is the optimizer’s contribution to the code you actually run. On this function it was 32%; on code with fewer compile-time constants it will be less, and the way to find out is one ini flag and one measurement.

Do not raise the level. Of the sixteen passes, the default 0x7FFEBFFF enables fifteen; the only one it leaves out is pass 15, whose own comment in the header calls it (unsafe) Collect constants.

Dump after pass 8 when a constant is not behaving the way you expect. If a value you thought was constant is still being read from a variable in that listing, something is stopping the propagation — a reference, a superglobal, a function call the optimizer cannot see through — and the listing will show which instruction still needs it.

And when a benchmark reports that an operation is free, check the listing before believing it. The engine is allowed to delete your experiment, and it does so at two different stages, only one of which OPcache controls. It works in the other direction too: a syntax feature that sounds expensive can turn out to emit a direct call, and the listing says so before any benchmark does.

Frequently asked

Does enabling OPcache make my code run faster, or just start faster?

Both, but by different mechanisms, and only one of them is the cache. With opcache.optimization_level=0 the same function cost 21.640 ns a call against 21.395 with OPcache off entirely - the caching saved compilation and nothing else. Turning the optimizer back on took it to 14.783.

How do I see what the optimizer did to my function?

opcache.opt_debug_level accepts the pass bits. 0x1 dumps after pass 1, 0x10 after pass 5 (CFG), 0x100 after pass 8 (SCCP), 0x2000 after pass 14 (DCE), and 0x20000 after the whole optimizer. Diff two of them and the difference is what that pass did.

Why did my microbenchmark of an arithmetic operation measure nothing?

Probably because both operands were literals and the compiler folded the expression before any of this. phpdbg, which never runs the optimizer, already prints ASSIGN CV1($r) int(65536) for a loop body of 2 ** 16.

Is opcache.optimization_level worth tuning?

Not upward - the default already enables everything except two passes. It is worth knowing about downward, because setting it to 0 is how you measure what the optimizer is doing for a particular piece of code, and because a benchmark run without OPcache has it at 0 by definition.

Written by

Alden Pike

Alden Pike writes about PHP internals, performance, architecture and production behavior — the layer beneath the frameworks. Measurements over assumptions, trade-offs over universal rules.

More about the author

Arrow keys to move, Enter to open.