闭包如何造成内存泄漏? [英] How do closures create memory leaks?

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

问题描述

我正在审核此演示文稿中的幻灯片: http://slid.es/gruizdevilla/memory

I was reviewing the slides in this presentation: http://slid.es/gruizdevilla/memory

并在其中一张幻灯片上显示此代码,提示它会造成内存泄漏:

and on one of the slides, this code is presented with the suggestion that it creates a memory leak:

var a = function () { 
   var smallStr = 'x',
   largeStr = new Array(1000000).join('x'); 

   return function (n) { 
        eval(''); //maintains reference to largeStr
        return smallStr; 
   }; 
}();




闭包可能是内存泄漏的另一个来源。了解闭包中保留的引用。

Closures can be another source of memory leaks. Understand what references are retained in the closure.

请记住:eval是邪恶的

And remember: eval is evil

有人可以在这里解释这个问题?

Can someone explain the issue here?

推荐答案

如果不是返回一个函数

    eval('');

您返回了一个通过其参数

you returned one that passes its argument

    eval(n);

然后有人可以拨打 a('largeStr')获取数组,因此JavaScript解释器无法对数组进行垃圾收集。

then someone could call a('largeStr') to get the array, so the JavaScript interpreter cannot garbage collect the array.

解释器可以意识到

eval('');

相当于

;

但大多数人都不够聪明,所以只要他们看到 eval 只要闭包可以到达,它们就会停止允许GC关闭变量。

but most are not smart enough to do that, so as soon as they see eval they stop allowing GC of closed-over variables as long as the closure is reachable.

eval 由于其输入的性质而无法有效访问已关闭的变量时,会出现内存泄漏:

The memory leak arises when eval can't effectively access closed-over variables because of the nature of its input:

eval('x' + (n-1));

由于'x'+(n-1)无法生成引用 largeStr 的JS字符串,没有输入可以导致 largeStr 被使用但它是仍然固定在记忆中。

Since 'x' + (n-1) can't produce a string of JS that references largeStr no input can lead to largeStr being used but it is still pinned in memory.

要看到整个行动,请使用

To see the whole thing in action, play around with

 var f = (function () {
     var a = [,,,,,];
     return function (x) { return eval(x); };
   })();
 alert(f('a.length'));

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

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