I always thought that object in javascript are simple key-value pair i.e. hash tables, but after reading this article I am confused.
The author specially says:
when you use an object as if it was a hash table, it will be turned into a hash table.
So, what the hell was it before? specially the whole para got me confused. Can somebody shed some light on?
Memory spaces in V8 “Variables in JavaScript (and most other programming languages) are stored in two places: stack and heap. A stack is usually a continuous region of memory allocating local context for each executing function. Heap is a much larger region storing everything allocated dynamically.
The V8 engine uses the Ignition interpreter, which takes in the Abstract Syntax Tree as the input and gives the byte code as the output, which further proceeds to the execution phase. When the code is being interpreted, the compiler tries to talk with the interpreter to optimize the code.
JS allocates memory for this object in the heap. The actual values are still primitive, which is why they are stored in the stack. const hobbies = ['hiking', 'reading']; Arrays are objects as well, which is why they are stored in the heap.
In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects. For more examples and explanations, see the JavaScript guide about functions.
According to this answer, in V8 there are two modes an object can have—Dictionary mode and Fast mode.
Objects are originally in fast mode where no hash map—no computation—is required for property access. It stores objects like structs in C. It's only once you start using an "object as if it was a hash table, it will be turned into a hash table"—dictionary mode. Once this happens, you get the performance penalty of a hash map being used behind the scenes for property access.
For example:
// running node with `--allow-natives-syntax` flag
var obj = { a: true, b: false };
%HasFastProperties(obj); // true (Fast mode)
delete obj.a;
%HasFastProperties(obj); // false (Dictionary mode)
Or:
var obj = { a: true, b: false };
%HasFastProperties(obj); // true (Fast mode)
// add lots of properties
for (var i = 0; i < 100; i++) {
obj["prop" + i] = i;
}
%HasFastProperties(obj); // false (Dictionary mode)
The reason it goes into dictionary mode when doing this is a performance optimization. It's faster to add/remove properties in dictionary mode than fast mode and so the V8 engine optimizes for changing structure instead of property access when it detects this behaviour (Read more here).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With