Guide to understand V8 internals and optimize JS
-
https://www.youtube.com/watch?v=_VHNTC67NR8
-
Locating value of an object's property in memory is an expensive process
-
shapes aka Hidden Classes in (Maps in V8)
-
JSObject ⇨ has Shape ⇝ Every property in the Shape has <..property information.. ∋ offset::Writable::Enumerable::Configurable>
-
Shape reduces Memory footprints
-
Transtion chains in V8 ⇨ Chain of Shapes ⇨ Happen when dynamically Add/Delete properties from a JS object whose Shape was already defined when the Js object was initialized
-
Transition chains ⇨ More lookup time by V8 Engine to find the property
-
Inline Caching (IC) ⇨ Every
function
has aFeedback Vector
, which caches the Shape of the objects passed as arguments -
Feedback Vector
cachesshape | properties | offset | state
of the argument object -
Feedback Vector
⇨state
cache ⇨ can have one of the three valuesmonomorphic property access
|polymorphic property access
|megamorphic property access
-
monomorphic property access
happens whenfunction
has been called with only one type ofshape
objects -
Monomorphic
property access speeds are 100 times faster thanMegamorphic
property access in a function -
How JS frameworks make property access
monomorphic
:
-
/*
Here property access is NOT monomorphic
**/
type Element{
fieldA;
fieldB;
};
type Component{
fieldC;
fieldD;
}
/** both the structures above are
combined to yield one Structure - Union of all */
/*
Here property access IS monomorphic
**/
type Node {
tag: nodeType;
fieldA | null;
fieldB | null;
fieldC | null;
fieldD | null;
}
- _BitFields
Array of bits
_
let effectTag = 0b010100111 //167
-
React uses BitFields to encode side effects, each bit in the field signifies what side effect to perform ie,
UPDATE
PLACEMENT
etc -
Advantages of BitFields
- No need to allocate memory for JS objects and shapes
- Simplified garbage collection
- Smaller and Contiguous memory usage
- Fast access using single bitwise operator
const effectTag = 0b000000000010
const effectTags ={
Placement: 0b000000000010,
Update: 0b000000000100,
PlacementAndUpdate: 0b000000001000
};
if(effectTag & effectTags.Placement){
...
}
- Bloom Filters _Data structure which answers
Definitely No
orMaybe
- used when answer is
no
most of the times -
let hashKeyFn = (value) => value.charCodeAt(0) % 8; let arr = ['John','Anna','Tom'] const hashKey = hashKeyFn(arr[0]) let bloomFilter = 0b00000000; bloomFilter = bloomFilter | hashKey let someValue = Value_Coming_From_Some_Scope() let isItPresent = (bloomFilter & hashKeyFn(someValue)) !== 0
- Do a Bloom Filters test before proceeding with actual comparisons in a deeply nested structures
- used when answer is