JavaScript compilation in V8

718 Views Asked by At

In the V8 home (the Google's JavaScript engine) we read this:

V8 compiles and executes JavaScript source code

  • Does it mean that JavaScript is not an interpreted language in V8?

  • Does V8 use a just-in-time compilation approach for JavaScript?


Edit: There is another existing question which already address my first question, but not the second.

1

There are 1 best solutions below

1
On BEST ANSWER

Does it mean that JavaScript is not an interpreted language in V8?

The answer to this is "it depends".

Historically V8 has compiled directly to machine code using its "full-codegen" compiler, which produces unoptimized code which uses inline caching to implement most operations such as arithmetic operations, load and stores of variables and properties, etc.

The code generated by full-codegen keeps track of how "hot" each function is, by adjusting a counter when the function is called and when it jumps back to the top of loops.

It also keeps track of the types of the variables used in each expression.

If it determines that a function (or part of a function) is very hot, and it has collected enough type information, it triggers the "Crankshaft" compiler which generates much better code.

However, the V8 developers are actively working on moving to a different system where they start off with an interpreter called "Ignition" and then use a compiler called "Turbofan" to produce optimized code for hot functions.

Here are a couple of posts from the V8 developers blog describing this:

Does V8 use a just-in-time compilation approach for JavaScript?

Yes, in a number of ways.

Firstly, it has a lazy parsing and lazy compilation mechanism. This means that when it parses a Javascript source file it parses the outermost scope eagerly, generating the full-codegen code immediately.

However, for functions defined within the file, it skips over them and just records the name of the function and the location of its source code. It generates a dummy function which simply calls into the V8 runtime to trigger the actual compilation of the function.

Secondly, it has a two stage compiler pipeline as described above, using either full-codegen+crankshaft or ignition+turbofan.

When the compilation is triggered it will initially generate unoptimized code or ignition bytecode (which it can do very quickly), and then later if the code is hot it triggers an optimized re-compilation (which is much slower but generates much better code).