Opcode Caching

Last updated on
29 August 2016

This documentation is incomplete. Add more information.

A common performance optimization for PHP is to enable an Opcode Cache.

What is an Opcode Cache?

PHP is a scripting language, which means that unlike some other languages, there is no compilation step before deployment. To execute, every file has to undergo three phases:

  1. Parse - File is read and parsed by the interpreter;
  2. Compile - File is compiled to opcode;
  3. Execute - Opcode is executed and code runs.
PHP execution vs Java execution
A compiled language like Java or C has a compilation step before deployment; an interpreted language like PHP compiles code just before it is executed.

Parsing and compiling every PHP file on every request is a big overhead. An Opcode Cache keeps a copy of the compiled script (opcode) in memory– so you can skip phases 1 and 2 and jump straight to execution.

The Alternative PHP Cache [APC] is arguably the most popular opcode cache, and is included in most installations of PHP up to version 5.5. Zend's Opcache was included by default in versions of PHP from 5.5 onwards.

Enabling and configuring APC

APC is widely used and well documented. It's unusual for APC to not be included with PHP.

The configuration that works best for you is highly dependent on your application server's workload. There is no one-size-fits-all configuration. All of the config keys are well documented in the PHP manual.

Below is a sample configuration; add this to your php.ini to get started with APC.

; Ensure APC is loaded. 
extension=apc.so;
; Ensure APC is enabled. 
apc.enabled=1; 
; Set the amount of memory for APC to use. 
apc.shm_size=96M 
; Check if a file has changed on every request; if so, regenerate the opcode cache for that file. 
; If this is set to 0 (off), then you may see a small performance boost, 
; but you will need to restart PHP to after any code change. 
apc.stat=1 
; The amount of time in seconds before cache entries are pruned. 
apc.ttl=86400