简体   繁体   中英

Why is the value of process.memoryUsage().heapUsed always increasing?

I have been trying to write a code where i can see heapused should not be increased when setting timeout and removing the next time. But regardless the heapUsed is constantly increasing.

let process = require('process');

console.log('initial', process.memoryUsage().heapUsed);

let timeout;
function happen() {
  
  console.log('process', process.memoryUsage().heapUsed);
  
  clearTimeout(timeout);             // Clear previous timeout
  timeout = setTimeout(happen, 500); // Set next timeout
  
}
happen();

Use setImmediate to clear the context when you call back Happen in your timeout :

x = setTimeout(function() {
    setImmediate(Happen);
}, 500);

The reason the heapUsed value is always increasing is due to the constant calling of the happen function. The happen function creates an Object to store the result of process.memoryUsage() , and a Timeout to store the result of setTimeout(...) .

These values which get created remain in the heap for an indefinite amount of time (until the garbage collector removes them). This article has more information related to javascript garbage collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM