My Feed
Create Team Blog
Let's kick off a fresh team blog! Bring on the crew and let's get to publishing.

Preloading in PHP 7.4

Brent Roose's photo
Brent Roose
·Jul 4, 2019

PHP 7.4 adds preloading support, a feature that could improve the performance of your code significantly.

In a nutshell, this is what preloading is about:

  • In order to preload files, you need to write a custom PHP script
  • This script is executed once on server startup
  • All preloaded files are available in memory for all requests
  • Changes made to the source file won't have any effect, until the server is restarted

Let's look at it in depth.

Opcache, but more

While preloading is built on top op opcache, it's not exactly the same. Opcache will take your PHP source files, compile it to "opcodes", and store those compiled files on disk.

You can think of "opcodes" as a low-level representation of your code, that can be easily interpreted at runtime. So opcache skips the translation step between your source files and what the PHP interpreter actually needs at runtime. A huge win!

But, there's more to be gained. Opcached files don't know about other files. If you've got a class A extending from class B, you'd still need to link them together at runtime. Furthermore, opcache performs checks to see whether the source files were modified, and will invalidate its caches based on that.

So this is where preloading comes into play: it will not only compile source files to opcodes, but also link related classes, traits and interfaces together. It will then keep this "compiled" blob of runnable code — that is: code usable by the PHP interpreter — in memory.

When a request arrives at the server, it can now use parts of the codebase that were already loaded in memory, without any overhead.

So, what "parts of the codebase" are we talking about? Continue to read on