PHP 8 Just in time compiler

Tags:

Another most exciting feature of PHP 8 is JIT (Just in time compiler). Below is quote from PHP RFC Proposal:

PHP JIT is implemented as an almost independent part of OPcache. It may be enabled/disabled at PHP compile time and at run-time. When enabled, native code of PHP files is stored in an additional region of the OPcache shared memory and op_array→opcodes[].handler(s) keep pointers to the entry points of JIT-ed code

PHP Execution

PHP scripts execution is 4 step process

  1. Lexing PHP first reads the code and then it prepares set of tokens.
  2. Parsing: The interpreter checks if the script matches the syntax rules and uses tokens to build an Abstract Syntax Tree (AST), which is a hierarchical representation of the structure of source code.
  3. Compilation: The interpreter traverses the tree and translates AST nodes into low-level Zend opcodes, which are numeric identifiers determining the type of instruction performed by the Zend VM.
  4. Interpretation: Opcodes are interpreted and run on the Zend VM.

JIT translates the hot parts of the intermediate code into machine code. Bypassing compilation, it will bring considerable improvements in performance and memory usage.

How does that work

There's a so called "monitor" that will look at the code as it's running. When this monitor detects parts of your code that are re-executed, it will mark those parts as "warm" or "hot", depending on the frequency. These hot parts can be compiled as optimised machine code, and used on the fly instead of the real code.