How v8 stores arrays in a fragmented memory

試著忘記壹切 提交于 2019-12-11 17:46:53

问题


I am wondering how v8 solves the problem of storing arrays in a fragmented memory. Basically, what is the array data structure in v8. I assume under the hood v8 has to deal with the problem of memory fragmentation. I have read that C allocated arrays with contiguous memory which makes sense since you are allocating it directly anyways. But with JavaScript it is dynamic so it seems you can't allocate them contiguously always.

Given memory blocks of 8 bytes free ○ and allocated ●, imagine this scenario.

○○○○○○○○○○○○○○○○○○○○○○○○○○○

Then you add an array of 5 items:

●●●●●○○○○○○○○○○○○○○○○○○○○○○

Then you add another array to a different part of memory:

●●●●●○○○○◖◖◖○○○○○○○○○○○○○○○

The question is, if you add 10 more items to the first array, how does it work:

●●●●●●●●●◖◖◖●●●●●●○○○○○○○○○

Wondering if you are keeping track of the array structure somewhere else instead of just the fact that they are contiguous (like in C).


回答1:


V8 developer here. Every array (both sparse/dictionary and dense/array mode) has one backing store for elements. When more elements are added than the backing store can hold, a new backing store is allocated and all elements are copied over. In this event the backing store is grown by a factor (not just one element), which is what gives you amortized-constant element addition performance. When not enough memory (or contiguous memory) for a new backing store is available, V8 crashes with an out-of-memory error.



来源:https://stackoverflow.com/questions/49991514/how-v8-stores-arrays-in-a-fragmented-memory

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