OPcache vs preloading in PHP

Published on March 22nd, 2024

Both techniques, OPcache and preloading, are used to improve the performance of PHP code.

OPcache

OPcache stands for "Opcode Cache," and it is a feature in PHP that helps improve the performance of PHP scripts by storing compiled code in memory.

When you run a PHP script, PHP needs to translate that script into machine-readable instructions, called opcodes, before executing it. This takes time and resources. OPcache stores these translated opcodes in memory so that PHP doesn't have to re-translate the script every time it's requested. Instead, it can quickly retrieve the already translated opcodes from memory, which makes the execution of PHP scripts faster and more efficient.

OPcache comes with PHP by default since version 5.5, so there is no need to set anything up. It can be enabled/disabled in the loaded php.ini file by commenting out opcache.enable=1. You can customise other settings related to OPcache in the php.ini file, such as memory allocation or cache expiration.

Preloading

Preloading is built on top of OPcache, and it does what it says on the tin - it preloades specific PHP files or classes into memory before they are needed. Having these files already available when the script runs saves time and resources because PHP doesn't have to load them again for each request.

Preloading needs to be set up, it doesn't come with PHP by default. You need to write a script telling the server which files to preload. It makes sense to call it preload.php (but it doesn't need to have this specific name) and then link it in the php.ini file using the opcache.preload directive:

opcache.preload=/path/to/preload.php

The preload.php script is a simple PHP script that might look something like this:

<?php

require_once '/path/to/important-file.php';
require_once '/path/to/another-important-file.php';
include_once '/path/to/not-essential-file.php';

You can use require_once or include_once, it doesn't matter which. The difference between these two is that both functions include a file, but if a file cannot be included, require_once will throw a fatal error and halt the execution of the script while include_once will just throw a warning, but the script will continue to execute. This means you should use require_once for crucial files and include_once for files that are not essential.

If a preloaded file has a dependency, this dependency also needs to be preloaded, PHP will not do it automatically.

You can use both OPcache and preloading together to really improve the performance of your PHP scripts, but not only that, it will make you feel really good about yourself 🤓.

← Go back