How does V8 manage the memory of object instances?

怎甘沉沦 提交于 2019-12-03 08:59:45

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    ]    
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!