Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

javascript - Finding JS memory leak in chrome dev tools

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.

enter image description here

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

Is the stuff under “Detached DOM Tree” just waiting to be garbage collected or are these real leaks?

Also does anyone know how to find out what function is holding on to a reference to a detached element?

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Simple example:

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

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

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();

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.

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.

Now here's the same jsfiddle but with:

delete parents.prevObject

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...