javascript - Memory efficient way to copy an array -
so i'm trying find memory-efficient way copy array. suppose have arr1
contains 500000 elements of value true
:
var arr1 = []; (var = 0; < 500000; i++) { arr1[i] = true; }
in node.js, occupies 32.3 mib (including 18.7 mib when node starts). now, when make reference arr1
, no memory allocated:
var arr2 = arr1;
now, when perform copy of arr1
arr2
:
var arr2 = arr1.concat();
the process occupies 36.2 mib, 4 mib.
here's thing: no matter empty or wipe original array, memory allocated array won't freed or picked garbage collector. suppose have:
arr1.length = 0; delete arr1; arr1 = undefined; arr1 = arr2.concat();
thanks that, process occupies 39.8 mib.
so happening here? there secret reference original array node (or whatever js engine out there) trying hide me? here's further code:
arr2.length = 0; delete arr2; arr2 = undefined; arr2 = arr1.concat();
which "empty" arr2
can hold copy of arr1
. may have figured out, i'm attemping transfer array's contents , forth, process occupies 43.5 mib. if large array, memory intake huge. there way this, taking memory efficienty account?
your profiling technique not correct.
i created array same way , created "a clone" same .concat()
method do, , here results
so can see it's same array (that takes ~2.06mb) retained 2 references.
the corresponding jsfiddle: http://jsfiddle.net/6o0h0r1j/
relevant reading:
to summarize: assumptions wrong beginning.
Comments
Post a Comment