开发者

How does V8 manage the memory of object instances?

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

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?


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 ] -/

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.

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           ]

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    ]    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜