[Node.js] global.gc() for Map and WeakMap

When you run node.js you can run 

node --expose-gc index.js

Which will allow you manully cleanup gc: global.gc()

 

Map

For map, it is easy to cost memory leak due to you have to clean up both key and value in order to let gc do it's job. If you just clean the key or value, then gc won't jump in:

const format = bytes => (bytes / 10247 /1024).toFixed(2) + 'MB'

global.gc()
const mem = process.memoryUsage()
cosnole.log(format(mem.heapUsed))

let map = new Map();
let key = new Array(5 * 1024 * 1024);
map.set(key, 1);

// since we delete both key and value, gc will work
map.delete(key);
key = null;

/*
map.delete(key);
// key = null; // only delete key, gc doesnt' work
*/

/*
// map.delete(key); // only delete value, gc doesnt' work
key = null; 
*/

global.gc();
const mem2 = process.memoryUsage();
console.log('Memory used after Map:', format(mem2.heapUsed));

 

posted @ 2024-11-26 20:41  Zhentiw  阅读(23)  评论(0)    收藏  举报