๐ŸŽ“ A1Learner
๐Ÿ”
0 of 27 lessons completed

OPcache and the JIT

A server can reuse work from earlier requests instead of starting every job from nothing. This lesson explains how PHP runs faster on a server.

A small loop, run fresh

This program adds the numbers 1 to 5 and prints the total. On a server, OPcache would keep the compiled form of this file after the first run.

<?php
$total = 0;
for ($i = 1; $i <= 5; $i++) {
  $total = $total + $i;
}
echo $total . "\n";

A function called many times

The loop calls the square function ten times and prints one total. A loop body that runs again and again is hot code.

<?php
function square(int $n): int {
  return $n * $n;
}
$total = 0;
for ($i = 1; $i <= 10; $i++) {
  $total = $total + square($i);
}
echo $total . "\n";

Example

<?php
$prices = [4, 6, 5];
$total = 0;
foreach ($prices as $price) {
  $total = $total + $price;
}
echo $total . "\n";
echo count($prices) . "\n";

Key points

  • Every PHP file is turned into a compiled form before its code runs.
  • OPcache is a store that keeps the compiled form of each file in shared memory.
  • A server compiles a file once, and later requests reuse the form OPcache kept.
  • Hot code is code that runs many times during one program run.
  • The JIT is a part of PHP that turns hot code into machine code while the program runs.
  • The command line tool on this machine runs each file fresh, and OPcache is not loaded in it.
  • A long-running server gains the most, since its cache stays warm across many requests.

In this example, a loop adds three prices and prints the total, then the count of prices prints. On a server this file would be compiled once and its form kept by OPcache. On the command line here the file runs fresh, and the same lines print.

Note

Short scripts gain little, since they end before a cache or hot code can matter much.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does OPcache keep in shared memory?