如何请求 node.js 中的垃圾收集器运行?
在启动时,我的 node.js 应用似乎使用了大约 200MB 的内存.如果我不理会它一段时间,它会缩小到 9MB 左右.
At startup, it seems my node.js app uses around 200MB of memory. If I leave it alone for a while, it shrinks to around 9MB.
是否可以在应用内:
- 检查应用使用了多少内存?
- 请求垃圾收集器运行?
我问的原因是,我从磁盘加载了一些文件,这些文件是临时处理的.这可能会导致内存使用量激增.但是我不想在 GC 运行之前加载更多文件,否则会有内存不足的风险.
The reason I ask is, I load a number of files from disk, which are processed temporarily. This probably causes the memory usage to spike. But I don't want to load more files until the GC runs, otherwise there is the risk that I will run out of memory.
有什么建议吗?
推荐答案
如果使用 --expose-gc
标志启动节点进程,则可以调用 global.gc()
强制节点运行垃圾回收.请记住,节点应用程序中的所有其他执行都会暂停,直到 GC 完成,所以不要太频繁地使用它,否则会影响性能.
If you launch the node process with the --expose-gc
flag, you can then call global.gc()
to force node to run garbage collection. Keep in mind that all other execution within your node app is paused until GC completes, so don't use it too often or it will affect performance.
您可能希望在从代码中进行 GC 调用时包含一个检查,这样如果节点在没有标志的情况下运行,事情就不会变坏:
You might want to include a check when making GC calls from within your code so things don't go bad if node was run without the flag:
try {
if (global.gc) {global.gc();}
} catch (e) {
console.log("`node --expose-gc index.js`");
process.exit();
}
相关文章