2

Given this code:

function init() {

    var id = 1234;

    $("button").click(function() {
        alert(id);
    });

}

Basically when init is called it adds a click function on to the button.

Now lets say the button gets removed from the DOM somehow by external code. Normally, from what I understand, the garbage collector will check if the click function can be removed as well.

Will the garbage collector fail to remove the click function since the function is referencing the id variable via a closure, hence creating memory leak or will the click function be removed as well together with the DOM element?

corgrath
  • 11,673
  • 15
  • 68
  • 99

1 Answers1

1

I just tried calling init() ten times to see the memory heap increasing, then I have removed the element to which I have attached the event with the init() function, and as you can see the memory heap does not go down.

enter image description here


I attempted again removing alert(id) from the event and the garbage collector worked this time.

enter image description here

GiamPy
  • 3,543
  • 3
  • 30
  • 51
  • So, it seems like it does result in memory leak. That's somewhat surprising though. Seems like this is a common pattern in JavaScript coding though, refereeing to a closure variable that is. – corgrath Sep 14 '15 at 10:51
  • [I think that this could be of interested.](http://stackoverflow.com/questions/11186750/memory-leak-risk-in-javascript-closures?rq=1) – GiamPy Sep 14 '15 at 10:52
  • There could be a chance that in order to garbage collector work you need to remove the events manually before removing the element. – GiamPy Sep 14 '15 at 10:54
  • Is it possible you can redo your test without the "alert" row that uses the "id"? Because I assume the click functions gets removed as well, if nothing links to it, or it doesn't use any closure variables. – corgrath Sep 14 '15 at 10:56
  • Just to confirm, without the reference it got cleared? – corgrath Sep 14 '15 at 10:59
  • 1
    Yes. I have removed `alert(id)` and used `remove()` a second after attaching the events to the element instead of instantly after. – GiamPy Sep 14 '15 at 11:00
  • If this answer has answered your question, please remember to accept it @corgrath, thank you. – GiamPy Sep 15 '15 at 10:32