If you’ve ever used PHP, you’ve likely discovered that it’s not the most efficient of languages. Currently, PHP is one of the best languages for web development because it’s easy to learn and it has many great features such as easy integration with MySQL, and object-oriented capabilities. But it also has a big flaw: performance.
PHP runs in a virtual machine. The job of the virtual machine is to take the code that is saved in the .php file, and turn it into something that the server can understand. Zend Engine is the most popular PHP engine (the PHP virtual machine) to date. It uses an interpreter execute your PHP code. Without getting into the boring details of how an interpreter works, it just interprets the PHP as the PHP file gets executed.
Facebook, which was written in PHP, faced the issue of performance, so they decided to write their own virtual machine that would use a different approach. Enter HHVM. HHVM, or the HipHop Virtual Machine, uses a JIT (just-in-time) compilation approach to achieve better performance.
JIT vs. Interpreter
An interpreter may have machine-readable instructions for different operations. When a file is executed using the interpreter, the interpreter will analyze the file and map the different operations in the code to their corresponding machine instructions. So $foo = $bar++; might point to 2 pre-compiled machine instructions in the interpreter. One for incrementing an integer, and one for assigning a new value to a variable.
The JIT approach, however, is much faster than an interpreter, and in many cases can be faster than static compilation. JIT combines the benefits of both interpreters and static compilation. The first time you run your PHP using HHVM’s JIT, it compiles your PHP to HipHop Bytecode (HHBC), which is a set of easily readable instructions for the HHVM engine. It then caches blocks of HHBC so that it doesn’t have to recompile every time. While the first time the PHP code is executed might be a bit slower, due to compilation time, every time after that will be dramatically faster than it would be using an interpreter.
One of the biggest advantages of JIT is that it can optimize your code for you. If it thinks there is a better way to map instructions to execute your code more quickly, it will recompile the PHP into new, more efficient, HHBC.
The Hack Language
In addition to the JIT engine, Facebook engineers have built an all new language based on PHP. It’s called Hack. Hack takes the PHP you’ve come to know and (occasionally) love, and added the benefits of C/C++ features. Features such as type annotations, generics, lambdas, etc. have been added while still retaining the semantics of traditional PHP.
To give a variable a data type of int, for example, your PHP code would change from:
$number = 3;
int $number = 3;
This follows the semantics of PHP while adding in useful C/C++ language features.
For more information on HHVM, visit http://hhvm.com