問題描述
在啟動時,我的 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();
}
這篇關于如何請求 node.js 中的垃圾收集器運行?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!