> your AI agent picks dependencies from memory; give it dated facts — try starlog.dev ↗ vet your agent's deps ↗ vibe-coding is fine. vibe-importing isn’t. — try starlog.dev ↗ vibe-importing isn’t fine ↗ your agent has never seen your private packages — try starlog.dev ↗ facts for private packages ↗ a linter for the dependencies your AI agent picks — try starlog.dev ↗ a linter for agent deps ↗ whois is redacted, cdns mask the rest — get the real operator — try whoisgeni.us ↗ who really runs that domain ↗ domain attribution that shows its work — full evidence chain — try whoisgeni.us ↗ domain intel w/ evidence ↗

← Back to Articles

Inside PHP-src: How the Zend Engine's Computed Goto and Refcounting Make PHP Surprisingly Fast

[ View on GitHub ]

Inside PHP-src: How the Zend Engine's Computed Goto and Refcounting Make PHP Surprisingly Fast

Hook

PHP's Zend VM uses computed goto dispatch to achieve 15-30% performance gains over traditional switch-based interpreters—a technique borrowed from GCC's internals that most developers have never heard of.

Context

When Andi Gutmans and Zeev Suraski rewrote PHP's core in 1999 to create the Zend Engine, they faced a fundamental problem: how do you build an interpreter that handles millions of web requests per day without melting servers? The original PHP/FI 2.0 was a simple CGI binary that parsed scripts on every request, regenerating parse trees and executing them directly. This was acceptable for personal homepages, but Yahoo!'s adoption of PHP in the late 1990s demanded something far more sophisticated.

The php-src repository contains the solution: a stack-based virtual machine that compiles PHP into opcodes, caches those opcodes in shared memory, and executes them through a dispatch loop optimized for modern CPU architectures. The Zend Engine introduced copy-on-write semantics to reduce memory allocations, a hybrid garbage collector to handle circular references, and a SAPI layer that lets PHP run in FastCGI, CLI, or embedded contexts. Despite being written in C and maintaining 25 years of backward compatibility, php-src powers roughly 77% of websites with known server-side languages—a testament to pragmatic engineering over theoretical purity.

Technical Insight

Tokens

AST

Opcodes

Computed Goto

Execute

Hook

Runtime Context

PHP Source Code

Lexer

re2c-generated

Parser

Bison LALR

Compiler

OPcache

Shared Memory

Zend VM

Stack Machine

Dispatch Loop

Label Addresses

Opcode Handlers

ADD/ECHO/FETCH

Garbage Collector

RefCount + Cycles

Memory Manager

Copy-on-Write

Extensions

MINIT/RINIT

SAPI Layer

CLI/FPM/CGI

System architecture — auto-generated

The Zend VM's execution model reveals why PHP performs better than its reputation suggests. After the lexer (re2c-generated) and parser (Bison-based LALR) transform source code into an abstract syntax tree, the compiler generates opcodes—simple stack machine instructions like ZEND_ADD, ZEND_FETCH_DIM_R, or ZEND_ECHO. These opcodes are stored in op_arrays with operands that reference variables, literals, or temporary values.

The magic happens in the VM's dispatch loop. On compilers supporting computed goto (GCC, Clang), the Zend VM uses label addresses instead of a switch statement. Here's a simplified view of how dispatch works:

// Traditional switch dispatch (slower)
while (1) {
    switch (opline->opcode) {
        case ZEND_ADD:
            // perform addition
            opline++;
            break;
        case ZEND_ECHO:
            // output value
            opline++;
            break;
        // hundreds more cases
    }
}

// Computed goto dispatch (15-30% faster)
static const void* dispatch_table[] = {
    &&ZEND_ADD_LABEL,
    &&ZEND_ECHO_LABEL,
    // ...
};

ZEND_ADD_LABEL:
    // perform addition
    opline++;
    goto *dispatch_table[opline->opcode];

ZEND_ECHO_LABEL:
    // output value
    opline++;
    goto *dispatch_table[opline->opcode];

Computed goto eliminates branch misprediction overhead because the CPU doesn't need to predict a many-way branch—it jumps directly to the next instruction handler. This optimization, combined with careful opcode ordering to maximize instruction cache hits, explains why PHP's interpreter outperforms many scripting languages despite lacking a traditional JIT (until PHP 8.0).

The refcounting model is equally clever. Every PHP value (zval) contains a reference count and type information. When you pass an array to a function, PHP doesn't copy it—it increments the refcount. Only when you modify the array does copy-on-write trigger:

typedef struct _zval_struct {
    zend_value value;  // union of possible types
    union {
        struct {
            zend_uchar type;
            zend_uchar type_flags;
            uint16_t extra;  // stores refcount behavior
        } v;
        uint32_t type_info;
    } u1;
    uint32_t u2;  // extra data for arrays/objects
} zval;

When you write $b = $a where $a is an array with 10,000 elements, PHP doesn't allocate 10,000 new elements. It shares the underlying HashTable structure and increments a refcount. Only when you write $b[0] = 'modified' does PHP perform a copy. This explains PHP's historically confusing behavior around array references but enables memory efficiency that most developers never notice.

OPcache builds on this foundation by serializing compiled op_arrays into shared memory segments. When a request arrives, PHP checks the file's mtime against the cached version and skips the entire lexer-parser-compiler pipeline if nothing changed. This is why preloading (loading specific files into opcache at startup) yields 30-50% performance improvements in production: you eliminate repeated compilation of framework code that never changes during deployment.

The garbage collector only activates when potential cycles are detected. Most PHP allocations are tree-shaped (request-scoped variables that disappear at request end), so aggressive cycle detection would waste CPU. Instead, PHP tracks "possible roots"—refcounted values that might participate in cycles. When this buffer fills, the GC runs a mark-and-sweep pass to identify unreachable cycles. This hybrid approach means PHP applications rarely pay GC costs unless they explicitly create circular references.

Gotcha

The single-threaded execution model is php-src's fundamental limitation. Each request runs in complete isolation with no shared state beyond opcache and external resources like databases. This means CPU-bound tasks—image processing, complex calculations, large XML parsing—block the entire request. You cannot parallelize work across cores within a single request without forking processes or calling external services. PHP 8.0's JIT helps with numeric operations, but the moment your code touches dynamic property access, magic methods, or type juggling, execution falls back to the interpreter. Real-world JIT gains often measure 5-15% on typical web applications, not the 3-4x improvements seen in synthetic benchmarks.

Extension compatibility creates operational headaches. PHP's internal API lacks stability guarantees across minor versions—a PECL extension compiled for PHP 8.1.2 might segfault on PHP 8.1.3. The executor globals, memory manager macros, and zval structure all change without deprecation warnings. This forces teams to either compile extensions from source for each PHP version or wait for PECL maintainers to catch up. Distributions help, but niche extensions (legacy database drivers, proprietary protocol handlers) become maintenance burdens. The lack of a stable ABI means you cannot simply drop a compiled extension into a new PHP version like you can with Python's limited API or Node.js native addons.

The type system's gradual retrofitting means internal structures pay runtime costs that modern JIT-compiled languages avoid. Union types require checking actual values at runtime since storage isn't specialized. Typed properties store type information separately rather than enabling tagged pointers or unboxed integers. Array operations that would benefit from homogeneous type knowledge ("this array contains only integers") cannot optimize because PHP's arrays are always heterogeneous HashTables. This is why Python with NumPy or JavaScript with typed arrays dramatically outperforms PHP on numerical workloads—the interpreter cannot assume anything about data layout.

Verdict

Use if: You're performance-engineering a large PHP deployment and need to understand why certain code patterns cause opcache invalidation or excessive refcount manipulation; you're building PECL extensions and must comprehend the executor's lifecycle and memory management to avoid segfaults; you're conducting security research on type juggling vulnerabilities or refcounting exploits; or you're debugging production issues that involve opcode cache corruption or unexpected memory behavior. Skip if: You're building web applications rather than PHP tooling—your time is better spent profiling application code with Blackfire or XHProof than compiling the interpreter from source; you want true async/await or multi-threaded execution, which requires architectural changes better served by Swoole or migrating to Node.js/Go; or you need stable extension APIs across PHP versions, since the internal API's instability will create more problems than building extensions solves. Most developers should treat php-src as essential infrastructure to understand conceptually but never touch directly—distributions handle builds far better than custom compilation workflows.