V8如何管理对象实例的内存?

时间:2011-09-14 08:11:00

标签: v8

http://code.google.com/apis/v8/design.html

上面的页面解释了v8团队用于启用快速属性访问的优化技术。

但它的对象实例怎么样?可以随时向对象添加新属性,因此应允许其大小增加。它是否只是使用默认大小分配内存,当它达到大小限制时创建一个新缓冲区并将旧实例复制到新缓冲区?或者还有另一个很酷的技巧?

1 个答案:

答案 0 :(得分:12)

V8中新分配的JavaScript对象看起来像(->表示“指向”):

[ class       ] -> ... ; pointer to the hidden class
[ properties  ] -> [empty array]
[ elements    ] -> [empty array] ; elements are properties with numeric names
[ reserved #1 ] -\
[ reserved #2 ]  |
[ reserved #3 ]  }- space reserved for "in object properties"
...............  |
[ reserved #N ] -/

在对象属性中预先分配的每个对象中都有一定的空间。 V8选择预分配属性的数量,具体取决于构造函数(例如,形式this.field = expr的赋值数量)和运行时分析。

当您向对象添加新属性时,V8首先尝试放入预先分配的对象内插槽。当对象内插槽耗尽时,V8开始将它们放入对象外属性数组中。属性名称和属性索引之间的映射存储在隐藏类中。例如,JS对象{ a: 1, b: 2, c: 3, d: 4} 可能看起来像:

[ class       ] -> [a: in obj #1, b: in obj #2, c: out obj #1, d: out obj #2]
[ properties  ] -> [  3  ][  4  ] ; this is linear array
[ elements    ]    
[ 1           ]
[ 2           ]

如果properties数组变得太大V8将规范化一个对象:将其属性转换为字典形式:

[ class       ] -> [ OBJECT IS IN DICTIONARY MODE ]
[ properties  ] -> [a: 1, b: 2, c: 3, d: 4, e: 5] ; this is classical hash table
[ elements    ]