Home > Enterprise >  "JavaScript heap out of memory" when trying to create large Array
"JavaScript heap out of memory" when trying to create large Array

Time:03-02

In order to solve a coding challenge involving large primes, I'm first trying to create an Array of length 999999999 with every element having the value "true." However, when I try to create this Array, I keep getting the error "FATAL ERROR: invalid table size Allocation failed - JavaScript heap out of memory."

I tried two ways of creating the Array and it happened both times.

let numbers = Array(999999999);
for (let i = 0; i < numbers.length; i  ) {
  numbers[i] = true;
}
let numbers = [];
for (let i = 0; i < numbers.length; i  ) {
  numbers.push(true);
}

I've tried using node --max-old-space-size to increase the memory limit up to 5GB but it still doesn't work.

I've read that the max length of an array in Javascript is 4294967296, which is significantly higher than 999999999, so I am a little confused as to why it isn't working.

I seem able to create the Array(999999999), the error happens when I try to assign the value true to each element.

Any advice would be much appreciated :)

CodePudding user response:

5 GB (or GiB) is not enough.

A boolean in an array in node.js needs an average of 9.7 bytes of memory.. So, you'd need 999,999,999 * 9.7 = around 9.7 GB (~9.03 GiB) of memory, but other things will live in this space too, so to be on the safe side, I'd allocate around 11 GiB for it.

Having an array of this size is probably never a great idea though. You should think about a different way to approach your problem. The point of the challenge is probably that you find a smart solution that does not need loops over one billion things.

CodePudding user response:

mate. You can think of that like it's infinite Loop. If you do something which is taking so much memory, then its bad idea. You need to find another approach. Kind regards

  • Related