空数组与未定义变量的内存开销? [英] Memory overhead of empty array vs undefined var?
问题描述
var Arr1;
var Arr2 = [];
(假设 Arr1 以未定义的 var 开始,稍后根据需要变为数组.)
(Assume Arr1 starts as an undefined var and it becomes an array later as needed.)
十亿个 Arr1 与十亿个 Arr2 的内存占用量是否相同?它们在技术上都是空的,但是 Arr2 是一个对象,这意味着在对象本身的定义中肯定有一些开销,对吗?
Would a billion of Arr1 have the same memory footprint as a billion of Arr2? They are both technically empty, but Arr2 is an object which means there must be some overhead in the definition of the object itself, right?
推荐答案
var Arr1
创建一个内存占用,该内存占用不包含对任何内容的引用.所以,是的,这样做是有成本的,但它是最小的.
var Arr1
creates a memory footprint that holds a reference to nothing. So, yes, there is a cost to this, but it is minimal.
但是,var Arr2 = []
创建了一个内存地址,该地址保存对新 Array 对象的引用,因此那里有更多的足迹.即使数组是空的,它也是一个 Array
对象的唯一实例,它本身使用单个 Array.prototype
来继承.真正占用内存的是数组的数量,因为即使是 10 亿个空数组也不必存储 Array.prototype
尚未存储的任何内容.即使有 10 亿个空数组,它们也只继承自一个 Array.prototype
对象,这就是存储数组原生 API 的地方.
But, var Arr2 = []
creates a memory address that is holding a reference to a new Array object, so there is more of a footprint there. Even though the array is empty, it is a unique instance of an Array
object, which, itself uses the single Array.prototype
to inherit from. It's the population of the Array that will really take up memory, since even a billion empty arrays don't have to store anything that is not already being stored by Array.prototype
. Even with a billion empty arrays, they all inherit from just one Array.prototype
object and that is where the native API for arrays is stored.
这篇关于空数组与未定义变量的内存开销?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!