Javascript内存泄漏:分离的DOM树 [英] Javascript Memory Leaks: Detached DOM tree

查看:182
本文介绍了Javascript内存泄漏:分离的DOM树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到浏览器的内存在我处于某种形式时开始增加(这在任务管理器中很明显)。在IE 9中,在使用一段时间后,这很容易超过500MB,而chrome则更具弹性(使用相同的测试可达到200MB)。

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).

我正在使用chrome开发人员工具来调试此问题。我注意到有大量的Detached DOM树:

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

我假设这可以确认存在内存泄漏。这是对的吗?
其次,我需要找出如何确定问题的根本原因。我知道您应该使用保留树来识别阻止这些物品被回收的原因。但我无法找到如何使用保留树。例如,上面屏幕截图中的保留树是什么意思?

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?

任何帮助将不胜感激。

推荐答案

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

There are many considerations to keep in mind when you write code that references DOM elements. But it all basically boils down to a couple of simple points -

a。在你的本地函数中,总是清除引用

a. Within your local functions always clear the reference

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

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

b. Never store references as part of element data .data()

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

c. Try not to use DOM references inside closures/inline handlers, instead pass identifiers

    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。 (在我的案例中它确实有很大帮助)

Yes, one can argue that searching elements can slow the page down, but the delay is very minimal when compared to the performance hit a huge heap causes esp. in large single page applications. Hence, #3 should be used only after weighing the pros and cons. (It did help significantly in my case)

更新

d。避免使用匿名函数 - 在分析/查看堆快照时,命名事件处理程序和本地函数将对您有所帮助。

d. Avoid anonymous functions - Naming your event handlers and local functions will help you a lot while profiling/looking at heap snapshots.

这篇关于Javascript内存泄漏:分离的DOM树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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