本文介绍了jQuery Memory Leak Suspicion的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为XML做一个AJAX请求。我这样做每一秒。我注意到我的内存使用量增长到数百兆字节。正如您可能想象的那样,客户对此并不满意。在各个地方做了一些阅读后,我怀疑功能关闭引起了我的头痛。我正在寻找可以获得的任何验证以及如何解决它的任何帮助。

I am making an AJAX request for XML. I am doing this every second. I notice that my memory usage grows into the hundreds of megabytes. As you might imagine, the customer is not happy with this. After doing some reading in various places, I suspect that function closures are causing my headache. I am looking for any verification that can be had as well as any help for how to fix it.

function PageManager () {
    var self = this;

    self.timeoutHandler = function () {
        $.ajax ({
            url: 'URLtoXML',
            type: 'post',
            cache: false,
            context: self,
            success: function (data) {
                var slf = this;
                var xmlDoc = $($.parseXML (data));
                xmlDoc.find ("tag_label").each (function () {
                    self.val = parseInt ($.trim ($(this).text ()));
                }
                setTimeout (slf.timeoutHandler, 750);
            }
        });
    }
}

var pm = new PageManager ();
pm.timeoutHandler ();

编辑我已合并了一些人的想法和一些成功的处理程序内部。我看到一个较小的增长率,但不是很多。

EDIT I have incorporated some people's ideas and a little of the success handler internals. I see a smaller growth rate, but not by much.

推荐答案

为了避免这种情况任何新创建的函数(上下文)正在关闭它的父作用域在这里,你只需要摆脱 setTimeout 中的匿名函数。所以

To avoid that any newly created function (context) is closing over its parent scope here, you would just need to get rid of the anonymous function in setTimeout there. So

 setTimeout(self.timeoutHandler, 750);

然而,即使该关闭将覆盖父母的上下文,任何一半体面的垃圾收集器(就像任何现代浏览器一样)会注意到它并在方法触发后释放内存。你没有提到的非常重要的事情是你注意到了哪种浏览器的行为。例如,Firefox垃圾收集器工作..非常不可思议(至少对我来说)。它将允许越来越多的内存被使用,然后在某些时候,它将再次释放一大块。

However, even if that closure would clouse over the parent(s) contexts, any half decent garbage collector (like any modern browser have) will notice it and free the memory after the method has fired. The very important thing you didn't mention is on which browser you noticed the behavior. The Firefox garbage collector for instance, works .. pretty unpretictable (at least to me). It'll allow for more and more memory to get used and then on some point, it will release a huge chunk again.

要查看发生了什么,请使用Firefox并在脚本运行时查看 about:memory
在那里你会看到内存的去向。如果内存使用量增加一段时间,我不会担心。看看它,如果这是你的所有代码,内存应该迟早被释放。

To see what is going on, use Firefox and have a look into about:memory while your script is running.There you will see where the memory goes. I would not be worried if the memory usage increases for a while. Look at it, if that is all of your code, the memory should get freed sooner or later.

这篇关于jQuery Memory Leak Suspicion的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 15:48