v8 如何存储快速对象

How v8 stores fast objects

作为 答案的后续问题,我想知道 v8 实际上是如何存储 "fast" 个对象的。

来自回答:

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.

然后我问 v8 是否 rehashes 当对象增长时,答案是:

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

(对于快速模式对象)

它还提到:

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

总而言之,即使您更改了对象属性,它仍然是结构化的,因此有一个隐藏的 class:

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

根据答案,v8 实际上并没有使用哈希表来存储值,因为它使用隐藏的 class。所以问题是,v8 实际上如何将值存储为隐藏的 class 结构。隐藏的class做什么,它是如何构造的,它是如何工作的。当您稍后在代码中执行 var d = 'd'; x[d] (只是为了使其动态化)时,它如何知道 d 的值在哪里而不将 d 属性 散列为字符串获取索引(理论上)。它如何从键中找到结构的内存地址。

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

C 中的结构是连续的数据块。属性存储在远离结构指针的固定偏移处。

例如

type Foo struct {
  x int32
  y int32
}

如果foo的内存地址是m,那么foo.xfoo.y的内存地址就是m+4m+8 , 分别。这里不需要哈希表。

V8 在编译时将 foo.x 映射到固定偏移量。

对于动态属性访问,上述内容不适用。