Enabling and configuring PHP OPcache

OPcache is said to improve PHP performance by storing scripts in shared memory thus avoiding the need to load scripts on each request.

Whilst seemingly basic, its setup and enabling is so simple that using OPcacheis important for a production instance even if it squeezes out minor speed gains.

Since PHP version 5.5.0 OPcache has been pre-packaged and only requires enabling rather than installing and enabling. That means your popular PHP versions like 7.3 and 7.4 have OPcache ready to go.

Enabling OPcache

To enable OPcache go into php.ini and set:

opcache.enable=1

Then restart apache:

sudo service apache2 restart

Now for tuning, The recommended settings from the PHP docs is:

opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60

You will find these settings in php.ini

Meanings

memory_consumption is the allocated memory for OPcache in MB.

interned_strings_buffer in MB the allowed memory for storing and saving strings across the whole PHP-fpm process.

max_accelerated_files How many files can be held in memory.

revalidate_freqIn seconds how often the cache should expire and be re-cached, 0 will mean each request it will be refreshed.

Better tuning

Depending on if you are in the development or production stage will determine your OPcache settings. revalidate_freq would be 0 for dev and up around 10-20 for production. Make sure max_accelerated_files is set at a value higher than your total count of files for the project. Up interned_strings_buffer to a value 12-16 and don’t be stingy with the memory_consumption although sometimes you have no choice.

opcache.memory_consumption=224
opcache.interned_strings_buffer=12
opcache.max_accelerated_files=4000
opcache.revalidate_freq=10

Make sure to save the php.ini once you are done editing and restart apache.

Using phpinfo(); is a quick way to see the status and settings of OPcache.