Javascript 如何请求 node.js 中的垃圾收集器运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27321997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to request the Garbage Collector in node.js to run?
提问by Kaizer Sozay
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.
在启动时,我的 node.js 应用程序似乎使用了大约 200MB 的内存。如果我不理会它一段时间,它会缩小到 9MB 左右。
Is it possible from within the app to:
是否可以从应用程序内:
- Check how much memory the app is using ?
- Request the garbage collector to run ?
- 检查应用程序使用了多少内存?
- 请求垃圾收集器运行?
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.
我问的原因是,我从磁盘加载了一些临时处理的文件。这可能会导致内存使用量激增。但是我不想在 GC 运行之前加载更多文件,否则会有内存不足的风险。
Any suggestions ?
有什么建议 ?
回答by IgnisFatuus
If you launch the node process with the --expose-gcflag, 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.
如果使用--expose-gc标志启动节点进程,则可以调用global.gc()强制节点运行垃圾收集。请记住,节点应用程序中的所有其他执行都将暂停,直到 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:
在从代码中进行 GC 调用时,您可能希望包含一个检查,这样如果节点在没有标志的情况下运行,事情就不会坏:
try {
if (global.gc) {global.gc();}
} catch (e) {
console.log("`node --expose-gc index.js`");
process.exit();
}
回答by Piqué
Node allows us to manually trigger Garbage Collection. This can be accomplished by running Node with --expose-gcflag (i.e. node --expose-gc index.js).
Once node is running in that mode, you can programmatically trigger a Garbage Collection at any time by calling global.gc()from your program.
Node 允许我们手动触发垃圾收集。这可以通过运行带有--expose-gc标志(即node --expose-gc index.js)的Node 来完成。
一旦节点在该模式下运行,您可以通过global.gc()从您的程序调用随时以编程方式触发垃圾收集。
ex -
前任 -
// Force garbage collection every time this function is called
try {
if (global.gc) {global.gc();}
} catch (e) {
console.log("`node --expose-gc index.js`");
process.exit();
}
回答by lwang135
One thing I would suggest, is that unless you need those files right at startup, try to load only when you need them.
我建议的一件事是,除非您在启动时就需要这些文件,否则请尝试仅在需要时加载。
EDIT: Refer to the post above.
编辑:请参阅上面的帖子。

