javascript - Memory consumption of sparse arrays in Node.js -


i have written small program produces arrays, runs quite long (almost forever ;-)):

var results = []; var = 1;  while (true) {   console.log(i++);   results.push([]); } 

when, instead of empty array, create sparse array of length i, program crashes quite fast:

var results = []; var = 1;  while (true) {   console.log(i);   results.push(new array(i++)); } 

actually i equal 17424, error message telling me

fatal error: call_and_retry_last allocation failed - process out of memory abort trap: 6 

and node.js takes me console. since difference second 1 produces "larger" empty arrays first ones, implies empty sparse array of length n takes n times space of empty array length 1.

am right (specifically node.js)?

one more question: if run

var results = []; var = 1;  while (true) {   console.log(i);   var temp = [];   temp[i++] = i;   results.push(temp); } 

then 1286175, again crashes with:

fatal error: call_and_retry_last allocation failed - process out of memory abort trap: 6 

why behave differently other 2 options?

ps: using node.js 0.12.0 run on os x.

when declare array size

array(1024); 

you doing allocates space 1024 elements. has allocate space up-front, because form of declaring array optimization stating

"i need reserve 1024 locations aren't resizing array push more elements onto it".

as know, declaring array [] still allows push unlimited number of elements onto it, array silently being resized (most memcpy()) behind scenes allow behaviour.

edit:

the reason higher iterations in second example, because using sparse array. sparse array doing

var arr = [] arr[1000000] = 1; 

does not mean array using 1,000,000 entries in memory. contrast dense array

var arr = array(1000000); 

which explicitly tells runtime reserve array can store 1000000 entries in memory.

related stackoverflow question: https://stackoverflow.com/a/1510842/276949


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -