V8 如何管理对象实例的内存? [英] How does V8 manage the memory of object instances?

查看:20
本文介绍了V8 如何管理对象实例的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

以上页面解释了 v8 团队用于实现快速属性访问的优化技术.

The above page explains the optimization technique v8 team uses to enable fast property access.

但是它的对象实例呢?新属性可以随时添加到对象中,因此应该允许它的大小增长.它是否只是简单地分配具有默认大小的内存,并且当它达到大小限制时会创建一个新缓冲区并将旧实例复制到新缓冲区?或者还有其他很酷的技巧?

But how about it's object instances? New properties can be added to the object anytime, so it should be allowed to grow in size. Does it simply allocate the memory with a default size and when it hits the size limit creates a new buffer and copy the old instance to the new buffer? Or there's another cool trick?

推荐答案

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

Newly allocated JavaScript object in V8 look like (-> means "points to"):

[ 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 形式的赋值次数)和运行时分析来选择预分配属性的数量.

There is a certain space in every object pre-allocated for so called in object properties. Number of pre-allocated properties is chosen by V8 depending on the constructor (e.g. number of assignments of the form this.field = expr) and runtime profiling.

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

When you add a new property to an object V8 first tries to put into pre-allocated in-object slot. When in-object slots are exhausted V8 starts putting them into out-of-object properties array. The mapping between property names and property indexes is stored in the hidden class. For example JS object { a: 1, b: 2, c: 3, d: 4} might look like:

[ 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 将规范化一个对象:将其属性转换为字典形式:

If properties array grows too big V8 will normalize an object: convert it's properties to a dictionary form:

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

这篇关于V8 如何管理对象实例的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆