Kuan
Kuan

Reputation: 11389

How this memory leak caused?

UPDATE: I guess I have to assume my understanding is right(probably, but if you have a better explanation, please let me know), it just needs to take a little more time for Chrome to GC the detached DOMs(I do not know how long it should take, a lot of times it does not GC at all for pretty long time)

enter image description here


All:

I am pretty new to Javascript memory management,when I read Google Chrome(Version 65.0.3325.181 (Official Build) (32-bit) Windows 7) Devtool tutorial, there is one example:

Discover detached DOM tree memory leaks with Heap Snapshots

var detachedNodes;

function create() {
  var ul = document.createElement('ul');
  for (var i = 0; i < 10; i++) {
    var li = document.createElement('li');
    ul.appendChild(li);
  }
  detachedNodes = ul;
}

document.getElementById('create').addEventListener('click', create);

I guess the reason is I have not understood how DOM works in memory.

My thought is: each time of clicking, an execution context built for create, a local var ul entered there referring the UL object generated in heap, then 10 li generated in heap, and connected with UL object, then the UL object gets referenced by detachedNode. And I thought: after the create()call, the reference between detachedNode and previous UL object will be broken(generated during the call to create() before this click), and document.createElement only creates but not appends, so that UL object should be GCed.

I wonder why that UL object in heap can not be GCed?

enter image description here

Upvotes: 1

Views: 118

Answers (1)

John Ellmore
John Ellmore

Reputation: 2229

If I click the button once, it creates that a DOM tree under that ul element, and then assigns it to the global detachedNodes variable (i.e. detachedNodes will reference that object in memory).

If I click it again, it'll assign a new ul element tree to detachedNodes, but now the old ul element won't be referenced any more. In this case, the ul tree from the first click will be garbage collected since no more references to it exist.

So to answer your question: yes, that first node can be garbage collected. The Google article you linked to doesn't seem to imply otherwise; it doesn't address clicking the button more than once at all from what I see.

Upvotes: 3

Related Questions