简体   繁体   English

复制数组的内存有效方式

[英]Memory efficient way to copy an array

So basically I'm trying to find a memory-efficient way to copy an array. 所以基本上,我试图找到一种内存有效的方式来复制数组。 Suppose we have arr1 which contains 500000 elements of value true : 假设我们有arr1 ,其中包含500000个值true元素:

var arr1 = [];

for (var i = 0; i < 500000; i++) {
    arr1[i] = true;
}

In Node.js, that occupies about 32.3 MiB (including 18.7 MiB when Node starts). 在Node.js中,大约占用32.3 MiB(包括Node启动时的18.7 MiB)。 Now, obviously when you make a reference to arr1 , no memory will be allocated: 现在,很明显,当您引用arr1 ,将不会分配内存:

var arr2 = arr1;

Now, when I perform a copy of arr1 into arr2 : 现在,当我将arr1复制到arr2

var arr2 = arr1.concat();

The process occupies 36.2 MiB, so about 4 MiB. 该过程占用36.2 MiB,所以大约4 MiB。

Here's the thing: no matter what I do to empty or wipe the original array, the memory allocated to that array won't get freed or picked up by the garbage collector. 事情是这样的:无论我要清空还是擦除原始数组,分配给该数组的内存都不会被垃圾收集器释放或占用。 Suppose I have: 假设我有:

arr1.length = 0;
delete arr1;
arr1 = undefined;

arr1 = arr2.concat();

Thanks to that, the process now occupies 39.8 MiB. 因此,该过程现在占用了39.8 MiB。

So what is really happening here? 那么,这里到底发生了什么? Is there some secret reference to the original array that Node (or whatever JS engine out there) is trying to hide from me? 是否存在对Node(或其他JS引擎)试图向我隐藏的原始数组的秘密引用? Here's further code: 这是更多代码:

arr2.length = 0;
delete arr2;
arr2 = undefined;

arr2 = arr1.concat();

Which will simply "empty" arr2 so it can hold a copy of arr1 . 它将简单地“清空” arr2以便可以保存arr1的副本。 As you may have figured out, I'm attemping to transfer the array's contents back and forth, but now the process occupies 43.5 MiB. 您可能已经知道,我正试图来回传输数组的内容,但是现在该过程占用了43.5 MiB。 If this was a large array, memory intake would be huge. 如果这是一个很大的数组,那么内存占用将是巨大的。 Is there a way to do this, taking memory efficienty into account? 有没有办法做到这一点,同时考虑内存效率?

Your profiling technique is not correct. 您的分析技术不正确。

I created an array the same way you do and created "a clone" with the same .concat() method as you do, and here are the results 我以与您相同的方式创建了一个数组,并使用与您相同的.concat()方法创建了一个“克隆”,这是结果

在此处输入图片说明

So as you can see it's the same array (that takes just ~2.06Mb) retained by 2 references. 因此,您可以看到它是由2个引用保留的同一数组(仅占用〜2.06Mb)。

The corresponding jsfiddle: http://jsfiddle.net/6o0h0r1j/ 对应的jsfiddle: http : //jsfiddle.net/6o0h0r1j/

Relevant reading: 相关阅读:

To summarize: your assumptions are wrong from the very beginning. 总结一下:您的假设从一开始就是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM