kenticny kenticny - 2 months ago 8x
Node.js Question

Javascript/Node.js array memory management

I have a scene of use array as a queue, and I have a question of this scene about the memory.

First, I create a array object in global, and create a producer to push the element to array uninterruptly.

var arr = [];

function runningProducer() {
setInterval(itemProducer, 50);

function itemProducer() {
var item = generateItem();
function generateItem() {
return { a: Math.random(), };

Then, I create a customer to clear the array in 1 second

function runningCustomer() {
setInterval(clearQueue, 1000);

function clearQueue() {
var t = arr.concat(arr);
arr = [];

And running the above functions for a period of time, I found the memory always growing.

setInterval(() => {
var mem = process.memoryUsage();
}, 2000);

I think the array should release the memory after set empty, but not.
Please give me some suggetions about this question, and is there any way to release the memory manually in javascript?


The answer to this question is in Barmar's comment. Reserved memory is not immediately released the moment it is no longer needed. JavaScript relies on garbage collection to detect unused references and release them back to the heap, but garbage collection is an expensive procedure so it is only run every once in a while.

When I try to run your code, the memory usage does increase for a minute or two, and then suddenly goes back to its original value when the garbage collection runs. Perhaps you simply didn't watch the log long enough?

You can manually run garbage collection and see this for yourself by running node with the --expose-gc flag and executing global.gc() but you should not do this in production code unless you have a very good reason.