JavaScript闭包中的内存泄漏风险 [英] Memory leak risk in JavaScript closures

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

问题描述

已解决



关于这个主题,网络上有很多矛盾的信息。感谢@John,我设法做出来,闭包(如下面使用)不是内存泄漏的原因,而且 - 即使在IE8 - 他们不是那么常见的人们声称。事实上,在我的代码只发生了一次泄漏,这证明不是很难解决。



从现在开始,我对这个问题的回答将是:

AFAIK,IE8泄漏的唯一时间是当事件附加/处理程序在全局对象上设置。 ( window.onload window.onbeforeunload ,...)。要解决这个问题,请参阅下面的答案。






> UPDATE:



我完全迷失了...经过一段时间挖掘文章,至少一个巨大的矛盾。虽然JavaScript Guru(Douglas Crockford)之一说:


因为IE无法完成工作,回收循环,它落在我们身上。如果我们显式地中断循环,那么IE将能够回收内存。根据微软,关闭是内存泄漏的原因。这当然是非常错误的,但它导致微软给程序员非常不好的建议,如何应对微软的错误。事实证明,很容易打破DOM边上的循环。


由于@freakish指出我下面的代码片段与jQuery的内部类似工作我觉得相当安全的我的解决方案不会造成内存泄漏。同时,我发现你可以找到一个类似的例子,虽然它不使用ajax,但是setTimeout,结果几乎是一样的。 (您可以跳过下面的代码,到问题本身)



我记住的代码是:

  function prepareAjax(callback,method,url)
{
method = method || 'POST';
callback = callback || success; //默认CB,只是记录/警告响应
url = url || getUrl(); // make default url / currentController / ajax
var xhr = createXHRObject(); // try {} catch等...
xhr.open(method,url,true);
xhr.setRequestMethod('X-Requested-with','XMLHttpRequest');
xhr.setRequestHeader('Content-type','application / x-www-form-urlencoded');
xhr.setRequestHeader('Accept','* / *');
xhr.onreadystatechange = function()
{
callback.apply(xhr);
}
return function(data)
{
//发送前对数据进行一些检查:data.hasOwnProperty('user')etc ...
xhr .send(data);
}
}



所有非常直观的东西,除了 onreadystatechange 回调。我注意到在绑定处理程序直接:IE的一些问题: xhr.onreadystatechange = callback; ,因此匿名函数。不知道为什么,但我发现这是使它工作的最简单的方法。



正如我所说,我使用了很多事件委托,所以你可以想象,它可能被证明是有用的访问实际元素/事件触发ajax呼叫。所以我有一些事件处理程序,看起来像这样:

  function handleClick(e)
{
var目标,父,数据,i;
e = e || window.event;
target = e.target || e.srcElement;
if(target.tagName.toLowerCase()!=='input'&&&target.className!=='delegateMe')
{
return true;
}
parent = target;
while(parent.tagName.toLowerCase()!=='tr')
{
parent = parent.parentNode;
}
data = {};
for(i = 0; i {
data [parent.cells [i] .className] = parent.cells [i] .innerHTML;
}
//数据看起来像{name:'Bar',firstName:'Foo',title:'Mr。'}
i = prepareAjax(function(t)
{
return function()
{
if(this.readyState === 4&& this.status === 200)
{
/ / check responseText,如果确定:
t.setAttribute('disabled','disabled');
}
}
}
i(data);
}



如你所见, onreadystatechange callback是一个函数的返回值,它在调用回调时提供对 target 元素的引用。由于事件委托,我不再需要担心可能绑定到该元素的事件,当我决定从DOM(我有时)删除它。

然而,在我看来,回调函数的调用对象可能对IE的JScript引擎及其垃圾回收器来说太多了:


Event ==> handler ==> prepareAjax是一个很正常的调用序列,但是回调参数:



[anon。 func(argument t = target)返回anon。 F(具有对t的访问,然后反过来将其引用回目标)]    ===>传递到anon回调函数,使用.apply方法调用xhr对象, em> private 变量到prepareAjax函数


我在FF和chrome测试了这个它在那里工作正常,但是这种类型的闭包关闭闭包时,每次传递一个DOM元素的引用是IE中的一个问题(尤其是在IE9之前的版本)?






不,我不会使用jQuery或其他libs。我喜欢纯JS,并且想尽可能多地了解这种严重低估的语言。代码片段不是实际的复制粘贴示例,但提供,IMO,一个很好的代表,我如何使用委托,闭包和回调在我的脚本。所以如果一些语法不是很对,请随时更正,但这不是这个问题是关于,当然。

解决方案

我曾经在微软的JavaScript程序管理器中使用非浏览器的EcmaScript JScr ... JavaScript)项目。我们对闭包进行了一些漫长的讨论。最后,关键是他们更难于GC,而不是不可能。我必须阅读DC的讨论,如何MS是错误,关闭导致内存泄漏 - 对于IE的旧实现,闭包肯定是有问题的,因为他们非常难以垃圾收集与MS实现<强>。我发现奇怪的是,一个雅虎的家伙会试图告诉MS建筑师他们的代码的已知问题是在别的地方。



请记住,上面引用的文章指的是IE6,因为IE7仍然处于在写作时的重大发展。



作为旁白 - 感谢上帝,IE6已经死了(不要让我挖掘葬礼图片)。虽然,不要忘记它的遗产...我还没有看到任何人做一个可信的论据,它不是世界上最好的浏览器在它的发布的第1天 - 问题是,他们赢得了浏览器的战争。所以,在相当于他们的历史的一个更大的失误之一 - 他们之后开火团队,它停滞了将近5年。 IE团队下降了4或5个人做错误修复多年,创造了一个巨大的人才流失,并大大落后于曲线。当他们重新聘用团队并意识到他们在哪里时,他们几年后,因为添加了一堆处理一个monolothic代码库,没有人真正理解了。这是我作为公司内部的观点,但不直接绑定到那个团队。



记住,IE从来没有针对闭包进行优化,因为没有ProtoypeJS(heck,没有Rails),而jQuery在Resig的头上只是一个闪光。



撰写本文时,他们仍然使用256 MB内存的机器,这些机器还没有到期。 p>

我认为只有公平地告诉你这个历史课,让我读完你的整本书的一个问题。



最后,我的观点是,你引用的材料是非常过时的。是的,避免在IE6中的关闭,因为它们会导致内存泄漏 - 但在IE6没有什么?



最后,这是一个问题,MS已解决和继续解决。



我知道他们在这个区域在IE8周围做了大量的工作(作为我的unmentionable项目使用非标准的JavaScript引擎),这项工作已经继续到IE9 / 10。 StatCounter(http://gs.statcounter.com/)表明,IE7的市场份额从一年前的6%下降到1.5%,在开发新网站时,IE7变得越来越不重要。您还可以开发用于引入JavaScript支持的NetScape 2.0,但这只是稍微不太蠢。



真的...不要尝试过度优化为不再存在的发动机的缘故。


Solved

There's a lot of contradictory information on the web, regarding this subject. Thanks to @John, I managed to work out that the closures (as used below) aren't the cause of memory leaks, and that -even in IE8- they're not that common as people claim. In fact there was only 1 leak that occurred in my code, which proved not that difficult to fix.

From now on, my answer to this question will be:
AFAIK, the only time IE8 leaks, is when events are attached/handlers are set on the global object. (window.onload,window.onbeforeunload,...). To get around this, see my answer below.


HUGE UPDATE:

I'm completly lost now... After some time digging through articles and tuts both old and new, I'm left with at least one humongous contradiction. While one of THE JavaScript Guru's (Douglas Crockford) says:

Since IE is unable to do its job and reclaim the cycles, it falls on us to do it. If we explicitly break the cycles, then IE will be able to reclaim the memory. According to Microsoft, closures are the cause of memory leaks. This is of course deeply wrong, but it leads to Microsoft giving very bad advice to programmers on how to cope with Microsoft's bugs. It turns out that it is easy to break the cycles on the DOM side. It is virtually impossible to break them on the JScript side.

And as @freakish pointed out that my snippets below are similar to jQuery's internal workings I felt pretty secure about my solution not causing memory leaks. At the same time I found this MSDN page, where the section Circular References with Closures was of particular interest to me. The figure below is pretty much a schematic representation of how my code works, isn't it:

The only difference being that I have the common sense of not attaching my event listeners to the elements themselves.
All the same Douggie is quite unequivocal: closures are not the source of mem-leaks in IE. This contradiction leaves me clueless as to who's right.

I've also found out that the leak issue isn't completely solved in IE9 either (can't find the link ATM).

One last thing: I've also come to learn that IE manages the DOM outside the JScript engine, which puts me in a spot of bother when I change the children of a <select> element, based on an ajax request:

function changeSeason(e)
{
    var xhr,sendVal,targetID;
    e = e || window.event;//(IE...
    targetID = this.id.replace(/commonSourceFragment/,'commonTargetFragment');//fooHomeSelect -> barHomeSelect
    sendVal = this.options[this.selectedIndex].innerHTML.trim().substring(0,1);
    xhr = prepareAjax(false,(function(t)
    {
        return function()
        {
            reusableCallback.apply(this,[t]);
        }
    })(document.getElementById(targetID)),'/index/ajax');
    xhr({data:{newSelect:sendVal}});
}

function reusableCallback(elem)
{
    if (this.readyState === 4 && this.status === 200)
    {
        var data = JSON.parse(this.responseText);
        elem.innerHTML = '<option>' + data.theArray.join('</option><option>') + '</option>';
    }
}

If IE really does manage the DOM as though the JScript engine weren't there, what are the odds that the option elements aren't deallocated using this code?
I've deliberately added this snippet as an example, because in this case I'm passing variables that are part of the closure scope as an argument to a global function. I couldn't find any documentation on this practice, but based on the documentation provided by Miscrosoft, it should break any circular references that might occur, doesn't it?



Warning: lengthy question... (sorry)

I've written a couple of fairly large JavaScripts to make Ajax calls in my web application. in order to avoid tons of callbacks and events, I'm taking full advantage of event delegation and closures. Now I've written a function that has me wondering as to possible memory leaks. Though I know IE > 8 deals with closures a lot better then its predecessors, it is company policy to support IE 8 all the same.

Below I've provided an example of what I'm on about, here you can find a similar example, though it doesn't use ajax, but a setTimeout, the result is pretty much the same. (You can, of course skip the code below, to the question itself)

The code I have in mind is this:

function prepareAjax(callback,method,url)
{
    method = method || 'POST';
    callback = callback || success;//a default CB, just logs/alerts the response
    url = url || getUrl();//makes default url /currentController/ajax
    var xhr = createXHRObject();//try{}catch etc...
    xhr.open(method,url,true);
    xhr.setRequestMethod('X-Requested-with','XMLHttpRequest');
    xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    xhr.setRequestHeader('Accept','*/*');
    xhr.onreadystatechange = function()
    {
        callback.apply(xhr);
    }
    return function(data)
    {
        //do some checks on data before sending: data.hasOwnProperty('user') etc...
        xhr.send(data);
    }
}

All pretty straight-forward stuff, except for the onreadystatechange callback. I noticed some issues with IE when binding the handler directly: xhr.onreadystatechange = callback;, hence the anonymous function. Don't know why, but I found this to be the easiest way to make it work.

As I said, I'm using a lot of event delegation, so you can imagine it may prove useful to have access to the actual element/event that fired the ajax call. So I have some event handlers that look like this:

function handleClick(e)
{
    var target,parent,data,i;
    e = e || window.event;
    target = e.target || e.srcElement;
    if (target.tagName.toLowerCase() !== 'input' && target.className !== 'delegateMe')
    {
        return true;
    }
    parent = target;
    while(parent.tagName.toLowerCase() !== 'tr')
    {
        parent = parent.parentNode;
    }
    data = {};
    for(i=0;i<parent.cells;i++)
    {
        data[parent.cells[i].className] = parent.cells[i].innerHTML;
    }
    //data looks something like {name:'Bar',firstName:'Foo',title:'Mr.'}
    i = prepareAjax((function(t)
    {
        return function()
        {
            if (this.readyState === 4 && this.status === 200)
            {
                //check responseText and, if ok:
                t.setAttribute('disabled','disabled');
            }
        }
    })(target));
    i(data);
}

As you can see, the onreadystatechange callback is the return value of a function, that provides the reference to the target element when the callback is called. Thanks to event delegation, I no longer have to worry about events that might be bound to that element, when I decide to remove it from the DOM (which I do sometimes).
To my mind, however, the call object of the callback function might prove too much for IE's JScript engine and its garbage collector:

Event ==> handler ==> prepareAjax is a pretty normal call sequence, but the callback argument:

[anon. func (argument t = target) returns anon. F (has access to t which in turn refs back to target)]
   ===> passed to a anon callback function, called using .apply method to the xhr object, in turn a private variable to the prepareAjax function

I've tested this "construction" in FF and chrome. It works just fine there, but would this kind of callstack of closure upon closure upon closure, on each occasion passing a reference to a DOM element be an issue in IE (especially versions prior to IE9)?


No, I'm not going to use jQuery or other libs. I like pure JS, and want to know as much as I can about this seriously underrated language. The code snippets are not actual copy-paste examples, but provide, IMO, a good representation of how I'm using delegation, closures and callbacks throughout my script. So if some syntax isn't quite right, feel free to correct it, but that's not what this question is about, of course.

解决方案

I used to work with the ex-program manager for JavaScript within Microsoft, on a non-browser EcmaScript (err.. JScr... JavaScript) project. We had some lengthy discussions about closures. In the end, the point is that they are harder to GC, not impossible. I'd have to read DC's discussion of how MS is 'wrong' that closures cause memory leaks -- for in IE's older implementations, closures were certainly problematic, because they were very hard to garbage collect with the MS implementation. I find it strange that a Yahoo guy would try to tell the MS architects that a known issue with their code was somewhere else. As much as I appreciate his work, I don't see what basis he had there.

Remember, the article you reference above refers to IE6, as IE7 was still under heavy development at the time of its writing.

As an aside -- thank god, IE6 is dead (don't make my dig up the funeral pictures). Although, don't forget its legacy... I've yet to see anyone make a credible argument that it wasn't the finest browser in the world on day 1 of its release -- the problem was that they won the browser war. And so, in what amounts to one of the larger blunders of their history -- they fired the team afterwards and it sat stagnant for nearly 5 years. The IE team was down to 4 or 5 guys doing bug fixes for years, creating a huge brain drain and falling behind the curve dramatically. By the time they rehired the team and realized where they were, they were years behind because of the added cruft of dealing with a monolothic codebase that nobody really understood anymore. That's my perspective as an internal in the company, but not directly tied to that team.

Remember too, IE never optimized for closures because there was no ProtoypeJS (heck, there was no Rails), and jQuery was barely a glimmer in Resig's head.

At the time of the writing, they were also still targeting machines with 256 megs of RAM, which also hadn't been end-of-life'd.

I thought it only fair to hand you this history lesson, after making me read your entire book of a question.

In the end, my point is that you're referencing material which is hugely dated. Yes, avoid closures in IE6, as they cause memory leaks -- but what didn't in IE6?

In the end, it is a problem that MS has addressed and continues to address. You're going to make some level of closures, that was the case, even back then.

I know that they did heavy work in this area around IE8 (as my unmentionable project used the non-at-the-time standard JavaScript engine), and that work has continued into IE9/10. StatCounter (http://gs.statcounter.com/) suggests that IE7 is down to a 1.5% market share, down from 6% a year ago, and in developing 'new' sites, IE7 becomes less and less relevant. You can also develop for NetScape 2.0, which introduced JavaScript support, but that would be only slightly less silly.

Really... Don't try to over-optimize for the sake of an engine which doesn't exist anymore.

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

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