Search code examples
javascriptv8

How v8 stores fast objects


As a follow-up question to the answer to If v8 rehashes when an object grows, I am wondering how v8 actually stores "fast" objects.

From the answer:

Fast mode is typically much faster for property access - but requires the object's structure to be known.

V8 will initially try to construct a template of what the object looks like called a "Hidden Class". The object will transform through hidden classes until V8 will give up and store the object as a slow property.

Then I asked if v8 rehashes when an object grows, and the answer was:

there is no hashing at all - it's just an offset of memory access - like a struct in C.

(for fast mode objects)

It also mentions:

objects aren't stored as hash maps at all in this case - it's a hidden class

So to summarize, even though you change the object properties, it is still structured so that there is a hidden class:

var x = { a: 1, b: 2, c: 3 }
x.d = 4
x.e = 5
x.f = 6

Based on the answer, v8 doesn't actually use a hashtable to store the values because it instead uses a hidden class. So the question is, how does v8 actually store the values as a hidden class struct. What does the hidden class do, how is it structured, how does it work. When you later in your code do var d = 'd'; x[d] (just to make it dynamic), how does it know where the value for d is without hashing the d property as a string to get the index (theoretically). How does it find the memory address of the struct from the key.


Solution

  • there is no hashing at all - it's just an offset of memory access - like a struct in C.

    A struct in C is a continuously block of data. The properties are stored at a fixed offset away from the struct pointer.

    For example in

    type Foo struct {
      x int32
      y int32
    }
    

    If the memory address of foo is m, the memory address of foo.x and foo.y will be m+4, m+8, respectively. Hashtable is not needed here.

    V8 maps foo.x to a fixed offset at compile time.

    For dynamic properties access the above does not apply.