您经常在web上看到使用闭包是JavaScript中大量内存泄漏的来源。大多数情况下,这些文章都提到混合脚本代码和DOM事件,其中脚本指向DOM,反之亦然。
我知道闭包在那里可能是个问题。
但是Node.js呢?在这里,我们自然没有DOM -所以不会像在浏览器中那样有内存泄漏的副作用。
闭包还会有什么其他问题?有没有人能详细说明或者给我推荐一个好的教程呢?
请注意,此问题明确针对Node.js,而不是浏览器。
发布于 2014-03-03 20:29:12
你可以在David Glasser的this blog post中找到一个很好的例子和解释。
好了,这就是(我添加了一些评论):
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,尤其要归功于它。
https://stackoverflow.com/questions/19550253
复制相似问题