Sneaky Wombat Sneaky Wombat - 7 months ago 32
Javascript Question

nodejs out of memory

I came across a curious issue today. This may be an easy answer for others, but it has me stumped. Why does the code below cause a memory error?

var cur = 167772160;
var bcast = 184549375;
var addresses = [];
while (cur <= bcast){
cur += 1;
addresses.push(cur);
}
addresses.length
addresses // memory goes from a few megs to over a gig in seconds when trying to print this


I get one of these two errors...the first when i run this code in node's interpreter and the latter when i run it through nodeunit:

FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory

FATAL ERROR: JS Allocation failed - process out of memory

ace ace
Answer

It happens when I try to access the array. But getting the length does not.

> var cur = 167772160;
> var bcast = 184549375;
> var addresses = [];
> while (cur <= bcast){
...   cur += 1;
...   addresses.push(cur);
... }
16777216
> addresses.length 
16777216
> addresses
FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory

Here's another SO question, memory limit in Node.js (and chrome V8) that relates to issue with memory usage.