How Javascript Engine's Work?
varunprashar5
Posted on June 29, 2021
๐๐ฎ๐๐ฎ๐๐ฐ๐ฟ๐ถ๐ฝ๐ ๐๐ป๐ด๐ถ๐ป๐ฒ is a program that executes the javascript code. These days relevant modern engines use just-in-time compilation for improved performance. (As per Wikipedia)
๐๐ถ๐ณ๐ณ๐ฒ๐ฟ๐ฒ๐ป๐ ๐๐๐ฒ๐ฝ๐ ๐ผ๐ณ ๐๐ฎ๐๐ฎ๐๐ฐ๐ฟ๐ถ๐ฝ๐ ๐ฒ๐ป๐ด๐ถ๐ป๐ฒ ๐ฝ๐ถ๐ฝ๐ฒ๐น๐ถ๐ป๐ฒ ๐ฎ๐ฟ๐ฒ (Generic for any JS Engine):
Javascript source code is passed to "Parser"
Parser divides the code into multiple tokens
It is converted into AST (Abstract Syntax Tree), a tree-like structure that represents functions, conditionals, scopes etc.
This AST is passed to the interpreter which converts the code into Bytecode.
At the same time engine is actually running the Javascript code
Bytecode is used by optimizing compiler along with profiling data
"Optimizing compiler" make certain assumptions based on profiling data and produces highly optimized machine code.
Sometimes there is a case where the 'optimization' assumption is incorrect and then it goes back to the previous version via the "Deoptimize" phase (where it actually becomes the overhead to us)
JS Engine usually optimizes "hot functions" and uses inline caching techniques to optimize the code.
๐๐ฒ๐'๐ ๐๐ฒ๐ฒ ๐๐ต๐ฒ๐๐ฒ ๐ถ๐ป ๐ฉ๐ด:
- Interpreter is called "Ignition".
- Optimizing compiler is called "TurboFan".
- Apart from Parser, there is a "pre-parser" that checks for syntax and tokens
๐ ๐ฟ๐ฒ๐ฐ๐ฒ๐ป๐ ๐๐ฝ๐ฑ๐ฎ๐๐ฒ ๐ถ๐ป ๐ฉ๐ด: "Sparkplug" is introduced which is present between "Ignition" & "TurboFan" which is also called Fast Compiler.
๐ก๐ผ๐๐ฒ: These are high-level step's that most of the JS engines goes through and every engine goes through their own set of steps for further optimizations.
They do have stack, heap, garbage collector and is out of scope for this post.
Do share more about JS engines in the comments
Checkout my youtube channel for more such content:
https://www.youtube.com/channel/UCJErruzdazYFQfDdb6avbtA
Posted on June 29, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.