33

I have noticed that the memory of the browser starts increasing whilst I am in a form (this is noticeable from the task manager). In IE 9, this goes easily over 500MB after some usage, whilst chrome is more resilient (goes to 200MB using same test).

I am using the chrome developer tools to debug this issue. I have noticed that there is a large number of Detached DOM tree:

detached dom tree screenshot

I am assuming that this can confirm that there is a memory leak. Would that be correct? Secondly, I would need to find out how to identify the root cause of the problem. I know that you should use the retaining tree to identify what is stopping those items from being reclaimed. But I cannot find out how to use the retaining tree. For example, what does the retaining tree in the above screenshot mean please?

Any assistance would be greatly appreciated.

4

2 回答 2

27

在编写引用 DOM 元素的代码时,需要牢记许多注意事项。但这一切基本上归结为几个简单的点 -

一个。在您的本地函数中始终清除参考

var menu = $('body #menu');
// do something with menu
 .
 .
 .
 menu = null;

湾。永远不要将引用存储为元素数据的一部分.data()

C。尽量不要在闭包/内联处理程序中使用 DOM 引用,而是传递标识符

    function attachClick(){
      var someDiv = $('#someDiv');

      someDiv.click(function(){
         var a = someDiv....;
         //Wrong. Instead of doing this..
      });


      someDiv.click(function(){
         var a = $('#someDiv');
         //Pass the identifier/selector and then use it to find the element
      });       


      var myFunc = function(){
         var a = someDiv;
         //using a variable from outside scope here - big DON'T!             
      }
    }

是的,有人可能会争辩说,搜索元素会减慢页面速度,但是与性能受到巨大堆导致的 esp 相比,延迟非常小。在大型单页应用程序中。因此,只有在权衡利弊后才能使用#3。(在我的情况下确实有很大帮助)

更新

d。避免匿名函数 - 命名您的事件处理程序和本地函数将在分析/查看堆快照时帮助您很多。

于 2013-06-05T09:57:10.237 回答
2

看起来您的代码创建了许多 DOM 子树并保留了 javascript 对其的引用。您需要从 Detached dom 树中选择一个元素。根据快照,您应该选择文本元素。并查看保持器树。

这棵树向您展示了使对象保持活动状态的所有路径。至少有一条路径,通常是最短的一条,将引导您到达窗口对象。如果您熟悉代码,那么您可能很容易在该路径中找到必须删除的对象,但事实并非如此。路径中可能有许多这样的对象。距离最小的物体更有趣。

于 2013-06-04T20:02:36.273 回答