Hi I'm relatively new to NodeJS and I'm currently trying to program a little CLI script that generates huge amounts of random numbers, pushes them into an array, then sorts them by the most occuring. It works well for amounts like 1 000 000 but whenever I try to generate really big amounts (e.g. 1 000 000 000), the Script crashes with this stacktrace:
FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory
I've tried increasing the Heap Memory with --max-old-space-size=8192
(I have 32GB of memory available) but it still crashes. My guess is NodeJS somehow ignores this command, as the error contains this:
<--- Last few GCs --->
[2492:00000152C6100D10] 18299 ms: Scavenge 878.8 (895.9) -> 863.1 (895.9) MB, 0.2 / 0.0 ms (average mu = 0.924, current mu = 0.923) allocation failure
[2492:00000152C6100D10] 18326 ms: Scavenge 878.8 (895.9) -> 863.1 (895.9) MB, 0.2 / 0.0 ms (average mu = 0.924, current mu = 0.923) allocation failure
[2492:00000152C6100D10] 18354 ms: Scavenge 878.8 (895.9) -> 863.1 (895.9) MB, 0.2 / 0.0 ms (average mu = 0.924, current mu = 0.923) allocation failure
To me it seems like it already crashes at fairly low amounts of memory consumption (900MB) as I also never see the Usage go above 1GB in the Task Manager. I've tested this on Node v14.15.4 and v15.7.0, my Windows 10 Version is 1909.
The function that generates the numbers looks like this:
const generate = async (base, upper, size, numbersWanted) => {
return new Promise((resolve, reject) => {
try {
console.log('Working...');
let myPool = [];
let counter = {};
// Generate the Pool and count each number generated
for (let x = 0; x < size; x++) {
let randomnum = getRandomNumber(base, upper);
myPool.push(randomnum);
if (counter.hasOwnProperty(randomnum)) counter[randomnum]++;
else counter[randomnum] = 1;
}
// Create an array of the occurred numbers and the amounts
let sortable = [];
for (let number in counter) {
sortable.push([String(number), counter[number]]);
}
// Sort the array by highest occurred numbers
sortable.sort(function(a, b) {
return b[1] - a[1];
});
// Slice of the not needed numbers that didnt occurr as much
let reduced = sortable.slice(0,numbersWanted);
let result = {
pool: myPool,
counter: counter,
wantedNumbers: reduced
};
resolve(result);
} catch (e) {
reject(e);
}
})
};
All the parameters (base, upperlimit etc.) are entered on Console with readline.
How do I get to run this with very big amounts? AFAIK Javascript Arrays can have multiple billion values, so this should be possible right?