如何防止 node.js 中的内存泄漏? [英] How to prevent memory leaks in node.js?

查看:35
本文介绍了如何防止 node.js 中的内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道 node.js 为我们提供了强大的力量,但强大的力量伴随着巨大的责任.

We know node.js provides us with great power but with great power comes great responsibility.

据我所知,V8 引擎不进行任何垃圾收集.那么我们应该避免哪些最常见的错误以确保我的节点服务器没有内存泄漏.

As far as I know the V8 engine doesn't do any garbage collection. So what are the most common mistakes we should avoid to ensure that no memory is leaking from my node server.

抱歉我的无知,V8 确实有一个强大的垃圾收集器.

Sorry for my ignorance, V8 does have a powerful garbage collector.

推荐答案

据我所知 V8 引擎没有进行任何垃圾收集.

As far as I know the V8 engine doesn't do any garbage collection.

V8 在构建中有一个强大而智能的垃圾收集器.

V8 has a powerful and intelligent garbage collector in build.

您的主要问题是不了解闭包如何维护对外部函数的范围和上下文的引用.这意味着您可以通过多种方式创建循环引用或创建不会被清理的变量.

Your main problem is not understanding how closures maintain a reference to scope and context of outer functions. This means there are various ways you can create circular references or otherwise create variables that just do not get cleaned up.

这是因为您的代码模棱两可并且编译器无法判断垃圾收集它是否安全.

This is because your code is ambigious and the compiler can not tell if it is safe to garbage collect it.

强制 GC 获取数据的一种方法是将变量清零.

A way to force the GC to pick up data is to null your variables.

function(foo, cb) {
    var bigObject = new BigObject();
    doFoo(foo).on("change", function(e) {
         if (e.type === bigObject.type) {
              cb();
              // bigObject = null;
         }
    });
}

v8 如何知道在事件处理程序中对大对象进行垃圾回收是否安全?它不是,所以您需要通过将变量设置为 null 来告诉它不再使用它.

How does v8 know whether it is safe to garbage collect big object when it's in an event handler? It doesn't so you need to tell it it's no longer used by setting the variable to null.

阅读各种文章:

这篇关于如何防止 node.js 中的内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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