在节点中手动运行垃圾收集 [英] Running garbage collection manually in node

查看:37
本文介绍了在节点中手动运行垃圾收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 node 并且正在考虑在 node 中手动运行垃圾收集.这有什么缺点吗?我这样做的原因是节点似乎没有足够频繁地运行垃圾收集.有谁知道 V8 在 node 中多久执行一次垃圾收集例程?

I am using node and am considering manually running garbage collection in node. Is there any drawbacks on this? The reason I am doing this is that it looks like node is not running garbage collection frequently enough. Does anyone know how often V8 does its garbage collection routine in node?

谢谢!

推荐答案

实际上,我在具有 1GB 实例的 heroku 上运行节点时遇到了同样的问题.

I actually had the same problem running node on heroku with 1GB instances.

在生产流量上运行节点服务器时,内存会不断增长,直到超过内存限制,导致运行缓慢.

When running the node server on production traffic, the memory would grow constantly until it exceeded the memory limit, which caused it to run slowly.

这可能是由于应用程序生成了大量垃圾造成的,它主要提供 JSON API 响应.但这不是内存泄漏,只是未收集的垃圾.

This is probably caused by the app generating a lot of garbage, it mostly serves JSON API responses. But it wasn't a memory leak, just uncollected garbage.

节点似乎没有优先为我的应用程序在旧对象空间上进行足够的垃圾收集,因此内存会不断增长.

It seems that node doesn't prioritize doing enough garbage collections on old object space for my app, so memory would constantly grow.

手动运行 global.gc()(通过节点 --expose_gc 启用)每次将减少 50MB 的内存使用量,并使应用程序暂停约 400 毫秒.

Running global.gc() manually (enabled with node --expose_gc) would reduce memory usage by 50MB every time and would pause the app for about 400ms.

我最终做的是按照随机计划手动运行 gc(这样 heroku 实例不会一次全部执行 GC).这减少了内存使用并停止了内存配额超出错误.

What I ended up doing is running gc manually on a randomized schedule (so that heroku instances wouldn't do GC all at once). This decreased the memory usage and stopped the memory quota exceeded errors.

一个简化的版本是这样的:

A simplified version would be something like this:

function scheduleGc() {
  if (!global.gc) {
    console.log('Garbage collection is not exposed');
    return;
  }

  // schedule next gc within a random interval (e.g. 15-45 minutes)
  // tweak this based on your app's memory usage
  var nextMinutes = Math.random() * 30 + 15;

  setTimeout(function(){
    global.gc();
    console.log('Manual gc', process.memoryUsage());
    scheduleGc();
  }, nextMinutes * 60 * 1000);
}

// call this in the startup script of your app (once per process)
scheduleGc();

您需要在公开垃圾收集的情况下运行您的应用:

You need to run your app with garbage collection exposed:

node --expose_gc app.js

这篇关于在节点中手动运行垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆