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

查看:84
本文介绍了如何防止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天全站免登陆