5

I wanted t create a large array in Javascript and wrote the following code but it did not work due to OOM

let N = 125000000;
let numbers = [];
for (let i = 0; i < N; i++) {
    numbers[i] = Math.round(Math.random()*10000);
}

Then I wrote "let numbers = new Array(N);" instead, which worked for the N (125000000) but did not work with larger N (200000000). Then I used Uint32Array, which worked for even larger N. It worked up to N = 2^31-1. Is there any limit on size in [], new Array(size), Uint32Array in Javascript? I guess the max size o Uint32Array is 2^31-1. I also want to know why new Array(N) has higher limit than []. Thank you

1
  • 1
    I guess If you're putting numbers into Array literal ([]) or Array Object (new Array(size)) they are stored as signed 64-bit Floating Point number - 64bits and If you're putting numbers into UInt32Array they are stored as unsigned 32-bit int numbers - 32bits. So, RAM-usage is twice less than in the first case. Commented May 27, 2019 at 17:58

1 Answer 1

2

NodeJS follows the ECMAScript specification, that is implemented via the V8 engine.

The maximum you can fit inside is 4,294,967,295 = 4.29 billion elements.

You ran out of memory because V8 sets a memory limit, you can bypass this limit by invoking Node with 'max-old-space-size' parameter, like so:

node --max-old-space-size=1024 yourscript.js

Where 1024 is 1GB, 2048 2GB and so goes on.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.