在chrome dev工具中查找JS内存泄漏 [英] Finding JS memory leak in chrome dev tools

查看:548
本文介绍了在chrome dev工具中查找JS内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果某些JS代码中存在内存泄漏,我正在使用chrome dev工具来解决问题。 内存时间轴看起来很好,内存按预期回收。

I’m using the chrome dev tools to work out if there is a memory leak in some JS code. The memory timeline looks good with memory being reclaimed as expected.

然而,内存快照令人困惑,因为它看起来像是泄漏,因为分离的DOM树下有条目。

However, the memory snapshot is confusing because it appears like there is a leak because there are entries under "Detached DOM Tree".

分离的DOM树下的东西是等待垃圾收集还是这些真正的泄漏?

也有人知道如何找出对分离元素的引用持有什么函数吗?

推荐答案

这些元素在代码中被引用,但它们与页面的主DOM树断开连接。

Those elements are being referenced in your code but they are disconnected from the page's main DOM tree.

简单示例:

var a = document.createElement("div");

a 现在引用断开连接的元素,它当 a 仍在范围内时,无法进行GC。

a references a disconnected element now, it cannot be GC'd when a is still in scope.

如果分离的dom树在内存中持续存在,那么你正在保持对它们的引用。使用jQuery这样做有点容易,
只保存对遍历结果的引用并保留它。例如:

If the detached dom trees persist in memory then you are keeping references to them. It is somewhat easy with jQuery to do this, just save a reference to a traversed result and keep that around. For example:

var parents = $("span").parent("div");
$("span").remove();

现在引用了跨距,即使看起来你无论如何都没有引用它们。 parents 通过jQuery .prevObject 属性间接保留对所有跨度的引用
。所以做 parents.prevObject 会给出引用所有跨度的对象。

Now the spans are referenced even though it doesn't appear you are referencing them anyhow. parents indirectly keeps references to all the spans through the jQuery .prevObject property. So doing parents.prevObject would give the object that references all the spans.

参见这里的示例 http://jsfiddle.net/C5xCR/6/ 。即使直接看起来不会引用跨度,但是
它们实际上是由 parents 全局变量引用的,你可以看到1000个跨度分离的DOM树永远不会消失。

See example here http://jsfiddle.net/C5xCR/6/. Even though it doesn't directly appear that the spans would be referenced, they are in fact referenced by the parents global variable and you can see the 1000 spans in the Detached DOM tree never go away.

现在这里是相同的jsfiddle但是:

Now here's the same jsfiddle but with:

delete parents.prevObject

你可以看到跨度不再是分离的dom树,或任何地方。 http://jsfiddle.net/C5xCR/7/

And you can see the spans are no longer in the detached dom tree, or anywhere for that matter. http://jsfiddle.net/C5xCR/7/

这篇关于在chrome dev工具中查找JS内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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