[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 @   Zhentiw  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2022-11-26 [XState] raise event: trigger an action immediately when reach target state
2022-11-26 [Typescript] 118. Hard - IsRequiredKey
2022-11-26 [Typescript] 117. Hard - ClassPublicKeys
2020-11-26 [RxJS] Filtering operator: first
2020-11-26 [Tools] Interactively exploring a large JSON file with fx
2020-11-26 [Javascript] Broadcaster + Operator + Listener pattern -- 22. mapError, wrap fetch with broadcaster with cancellation
2020-11-26 [Javascript] Cancel a promise
点击右上角即可分享
微信分享提示