V8 Engine: Basic Overview
What is V8 Engine?
V8 Engine is Not a physical entity like bike engine, its a JavaScript engine means just a big program who does lots of work to
execute our JavaScript code .
What it does?
* It compile your code ,Convert it into machine code and displays output.
* It also maintains Call stacks (which comes in picture while executing function), memory heap.
* It also manage garbage collection
So all browser use V8 ?
Definitely not. All browsers have their respective JavaScript engines.
Chrome →V8
Firefox → SpiderMonkey (First JavaScript Engine Netscape navigator which then evolved as SpiderMonkey)
Internet Explorer & Edge → Chakra
Safari → JavaScriptCore
Even anyone can create their own JS Engine , they just need to follow some standard like following ECMA.
How basically V8 engine executes our JavaScript code ?
V8 Uses JIT(Just in Time compilation)
full-codegen and Crankshaft are two compiler getting used
before V8 version 5.9, but after that it is no longer used
Just like many language we can say that in one line “JS code is gets compiled and generate machine code and execution happens” but internally
lots of process happen
Languages like java , CPP use AOT as name suggests ahead of time compilation. means code that is going to execute in future
is already compiled. but JavaScript , python doesn’t follow this approach. So to optimize execution JavaScript use JIT strategy which use both interpretation and compilation approaches.
V8 have Ignition Interpreter and TurboFan Compiler.
firstly scanner will take code and will make AST(Abstract Syntax Tree). after that it will go to Ignition interpreter then interpreter takes that tree and convert it into byte code. TurboFan provide optimized machine code for better execution
Garbage collection in V8
V8 Engine use mark and sweep algorithm for garbage collection.
In between execution it marks object for garbage collection(In internal thread not in execution thread)
by taking small pause between execution which also known as incremental marking.
Traditional mark and sweep algorithm mark unreachable object in heap and after they sweep out of memory
So that space can be allotted to new object. Incremental marking reduce that marking time by dividing it in
smaller chucks.
V8 Engine use concurrent marking to reduce GC time. it uses tri color strategy to mark objects, firstly all white
when initialized it turns grey and after sweep it turns out black.
V8 Engine is not just used in browsers but used in server-side-rendering like nodeJS