首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JavaScript中的内存泄漏和闭包-何时以及为什么?

JavaScript中的内存泄漏和闭包-何时以及为什么?
EN

Stack Overflow用户
提问于 2013-10-24 03:04:16
回答 1查看 29.2K关注 0票数 61

您经常在web上看到使用闭包是JavaScript中大量内存泄漏的来源。大多数情况下,这些文章都提到混合脚本代码和DOM事件,其中脚本指向DOM,反之亦然。

我知道闭包在那里可能是个问题。

但是Node.js呢?在这里,我们自然没有DOM -所以不会像在浏览器中那样有内存泄漏的副作用。

闭包还会有什么其他问题?有没有人能详细说明或者给我推荐一个好的教程呢?

请注意,此问题明确针对Node.js,而不是浏览器。

EN

回答 1

Stack Overflow用户

发布于 2014-03-03 20:29:12

你可以在David Glasser的this blog post中找到一个很好的例子和解释。

好了,这就是(我添加了一些评论):

代码语言:javascript
复制
var theThing = null;
var cnt = 0; // helps us to differentiate the leaked objects in the debugger
var replaceThing = function () {
    var originalThing = theThing;
    var unused = function () {
        if (originalThing) // originalThing is used in the closure and hence ends up in the lexical environment shared by all closures in that scope
            console.log("hi");
    };
    // originalThing = null; // <- nulling originalThing here tells V8 gc to collect it 
    theThing = {
        longStr: (++cnt) + '_' + (new Array(1000000).join('*')),
        someMethod: function () { // if not nulled, original thing is now attached to someMethod -> <function scope> -> Closure
            console.log(someMessage);
        }
    };
};
setInterval(replaceThing, 1000);

请在Chrome Dev工具(时间线选项卡,内存视图,单击记录)中使用和不使用originalThing进行尝试。请注意,上面的示例适用于浏览器和Node.js环境。

这也归功于Vyacheslav Egorov,尤其要归功于它。

票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19550253

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档