Lab 09: OPcache & JIT

Time: 40 minutes | Level: Advanced | Docker: docker run -it --rm php:8.3-cli bash

OPcache stores precompiled bytecode to eliminate repeated parsing. PHP 8.0+ includes JIT (Just-In-Time) compilation that translates hot PHP bytecode into native machine code, yielding significant speedups for CPU-intensive workloads.


Step 1: OPcache Fundamentals

OPcache works by caching the compiled bytecode of PHP files. In CLI mode, it's disabled by default.

<?php
// Check if OPcache is available
if (!function_exists('opcache_get_status')) {
    echo "OPcache extension not loaded\n";
    echo "Enable with: php -d opcache.enable=1 -d opcache.enable_cli=1 script.php\n";
    exit;
}

$status = opcache_get_status(false);

if ($status === false) {
    echo "OPcache available but disabled (CLI default)\n";
    echo "Enable with: php.ini → opcache.enable_cli=1\n";
} else {
    $mem = $status['memory_usage'];
    echo "OPcache Status:\n";
    echo "  Enabled:      " . ($status['opcache_enabled'] ? 'yes' : 'no') . "\n";
    echo "  JIT enabled:  " . ($status['jit']['enabled'] ? 'yes' : 'no') . "\n";
    echo "  Used memory:  " . number_format($mem['used_memory'] / 1024 / 1024, 2) . " MB\n";
    echo "  Free memory:  " . number_format($mem['free_memory'] / 1024 / 1024, 2) . " MB\n";
    echo "  Cached files: " . $status['opcache_statistics']['num_cached_scripts'] . "\n";
    echo "  Hit rate:     " . round($status['opcache_statistics']['opcache_hit_rate'], 2) . "%\n";
}

📸 Verified Output:


Step 2: OPcache Configuration Reference

📸 Verified Output:


Step 3: JIT Modes Explained

JIT compiles hot paths to native machine code. Two main modes:

📸 Verified Output:


Step 4: CPU Benchmark — Fibonacci

📸 Verified Output:


Step 5: Tight Loop Benchmark

📸 Verified Output:


Step 6: OPcache Preloading Concept

📸 Verified Output:


Step 7: OPcache Best Practices

📸 Verified Output:


Step 8: Capstone — Profiling Suite

📸 Verified Output:


Summary

Feature
Config/Function
Notes

Enable OPcache (CLI)

opcache.enable_cli=1

Off by default in CLI

JIT tracing mode

opcache.jit=tracing or 1255

Best for CPU workloads

JIT function mode

opcache.jit=function or 1205

Lower overhead

JIT buffer

opcache.jit_buffer_size=64M

Native code cache size

Check status

opcache_get_status()

Returns array or false

Get config

opcache_get_configuration()

All ini directives

Preloading

opcache.preload=preload.php

PHP-FPM only

Invalidate file

opcache_invalidate($path, true)

After deploy

Reset all

opcache_reset()

Full cache clear

JIT benefit

CPU-intensive code

3-5x speedup typical

JIT minimal gain

I/O bound, string ops

<10% improvement

Last updated