2

The PHP interpreter is converting as a first step the souce code into bytecode. In a second step, the bytecode is passed to a Zend Engie that creates the machine code for the relevant CPU. If opcache is activated, the bytecode is stored in cache, so that the first step can be skipped in subsequent calls.

Image from PHP Master Write Cutting Edge Code (Image taken from PHP Master Write Cutting-Edge Code)

However, I do not understand why opcache is caching bytecode instead of maschine code? Would it not be a big benefit if one could skip the first and second step? Also, since a website is in many cases only executed on one single server, I don't see that PHP is using the benefit of bytecode, which is (if I understood correctly) that the code can be used on different hardware.


About my research: Most questions that I found were about if PHP is interpreter or compiler language. The closest relevant question that I found was: Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter? - but here it was asked if it is possible to parse the bytecode beforehand and upload it (instead of caching). But my question is if the machine code can be cached instead of the bytecode.

Adam
  • 25,960
  • 22
  • 158
  • 247

1 Answers1

2

I am assuming that this is done so that there only needs to be one compilation strategy and leave it up to the OS dependant PHP interpreter to convert the OpCache to machine code that can run natively. Compare it to java, where the compilation artifacts are JVM bytecode and it's up to the JVM which is platform specific to turn this bytecode into executable machine code.

If PHP would have to know every possible platform (intel,amd,spark,arm,etc.) this would massively bloat OpCache compiler. However you usually only have the PHP runtime (refered to as Zend Engine in your diagram) that you need on your machine.

Anticom
  • 975
  • 13
  • 29
  • Yes, I see, PHP should not include every possible platform. I guess my question is rather, why does the Zend Engine not cache the machine code. I might create a new question for that. – Adam Jul 17 '19 at 08:26
  • 1
    Again assuming that this happens to a certain degree. The issue is that PHP is dynamically typed. So it might happen, that the Zend Engine has to throw away cached machine code because a new value came in as int and not as string as previously. There's lots of resources on Chromes compiler and optimizer. I know JS is kind of unrelated but most of the principles and inherent problems apply to both languages. – Anticom Jul 17 '19 at 08:36
  • So you say the machine code is probably cached, but its the job of the VM and depends on the OS? – Adam May 16 '20 at 08:38