V8 engine is at the heart of executing JavaScript. It’s is an open-source, high-performance JavaScript and WebAssembly engine written in C++. It is used in Google Chrome and Node.js, enabling fast JavaScript execution both in the browser and on the server side.
But what exactly is V8, and how does it make Node.js so efficient? In this article we will explores the inner workings of V8.
What is V8?
v8’s primary function is to take JavaScript code and execute it. However, V8 doesn't just interpret the code line by line, It includes features like Just-In-Time (JIT) compilation, garbage collection, and optimisation techniques to improve performance.
From JavaScript to Machine Code
Traditionally, JavaScript was interpreted, meaning each line of code was executed one at a time. This process can be slow. V8, on the other hand, uses a Just-In-Time (JIT) compiler.
The V8 Execution Process
Here's a simplified breakdown of the process:
Parsing: V8 first parses the JavaScript code, creating an Abstract Syntax Tree (AST). This tree represents the structure of the code.
(Interpreter): V8's interpreter, takes the AST and converts it into bytecode. Bytecode is an intermediate representation that is easier to execute than raw JavaScript but not as fast as machine code.
Compilation (Crankshaft): Initially, V8 uses a baseline compiler (called Crankshaft in older versions, but now Turbofan is the primary optimising compiler). This compiler quickly generates machine code.
Optimization : V8 monitors the running code. If it identifies frequently executed "hot paths" (parts of the code that are run often), it uses a more sophisticated optimising compiler (Turbofan) to generate highly optimised machine code. This optimisation happens in the background while the code is running.
Deoptimisation: Sometimes, V8 makes assumptions during optimisation. If these assumptions turn out to be incorrect (e.g., a variable's type changes), V8 can deoptimise the code and revert to the baseline compiler. This ensures correctness.
V8 and Node.js Performance:
V8's efficiency directly translates to Node.js's performance. The JIT compilation and other optimisations allow Node.js applications to run quickly and handle a large number of concurrent requests. This makes Node.js suitable for building high-performance web servers and other applications.
Further Reading:
https://www.freecodecamp.org/news/javascript-under-the-hood-v8/
https://hyperskill.org/learn/step/41307
https://www.geeksforgeeks.org/explain-the-role-of-v8-engine-in-nodejs/
Summary
By using JIT compilation, garbage collection, and optimisations like inline caching, V8 ensures JavaScript runs at high speed both in browsers and in Node.js.