Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript garbage collect this?

Every once in a while I find myself doing something along the lines of the following

var img = new Image();
img.src = 'php/getpic.php?z=' + imid + '&th=0';
img.onload = function(){drawImages(img,contexts,sizes)};

Explanation

  1. Create an HTML image element.
  2. Assign its src attribute
  3. Assign its onload event
  4. Pass one or more Canvas contexts to the event handler
  5. Draw the loaded image to the canvases

The thing I am not clear about is this - will the JavaScript garbage collector deal with the task of discarding the img element or do I need to do it myself or else face a slooow memory leak?

like image 810
DroidOS Avatar asked Nov 20 '12 15:11

DroidOS


People also ask

How does garbage collection in JavaScript work?

The garbage collector takes roots and “marks” (remembers) them. Then it visits and “marks” all references from them. Then it visits marked objects and marks their references. All visited objects are remembered, so as not to visit the same object twice in the future.

Which objects are garbage collected?

An object is eligible to be garbage collected if its reference variable is lost from the program during execution. Sometimes they are also called unreachable objects. What is reference of an object?

What is JavaScript garbage value?

An object with zero references is considered to be garbage or “collectible”. Example: javascript.

Which objects are garbage collected in Java?

What is Java Garbage Collection? Java applications obtain objects in memory as needed. It is the task of garbage collection (GC) in the Java virtual machine (JVM) to automatically determine what memory is no longer being used by a Java application and to recycle this memory for other uses.


2 Answers

It will leak in IE 6 and 7 (and very old versions of FF) because it creates a circular reference between JavaScript and the DOM. IE 6 and 7 can't garbage collect any objects which have circular references between the two worlds because they use separate garbage collectors.

Modern browsers can handle this without leaking.

To prevent it from leaking in IE 6 and 7, do this when you're done with img:

img.onload = null;

If you only care about modern browsers, you don't have to worry about it. (I'm so glad IE 6 and 7 are finally low enough in market share to suggest that!)


Update

The function you assign to onload creates a closure. That closure contains a reference to img. img can't be garbage collected from the DOM's memory as long as that closure exists in JScript's memory (JScript is name for the IE implementation of JavaScript). Likewise, the closure can't be garbage collected from JScript's memory as long as img exists in the DOM's memory, because img.onload has a reference to your function. This is a circular reference. In other words, just because drawImages executes once doesn't mean it won't execute again (the JScript engine doesn't know onload only fires once -- that's the DOM's domain), so JScript has to keep the closure alive.

The pattern you have shown is the classic pattern that is known to create memory leaks in IE 6 & 7. It consists of (1) A DOM node, (2) An event handler on that DOM node which creates a closure, and (3) A reference back to that DOM node inside the closure.

like image 123
Nathan Wall Avatar answered Sep 22 '22 10:09

Nathan Wall


If you are worried about memory leak what I suggest you is to use the Heap Debugger of Google Chrome. In your case I have made a simple test that can verify if your particular pattern will create a memory leak.

<html>
    <head>
        <script>
            function test() {
                var img = new Image();
                img.src = 'php/getpic.php?z=1&th=0';
                img.onload = function(){ drawImages(img,contexts,sizes); };
            }
        </script>
    </head>
    <body>
        <input type="button" onclick="test()" value="test" />
    </body>
</html>

I recommend you to press "test" once before the test to avoid unnecessary noise in the result (there are thing which get added in the memory the first time the code runs and this doesn't mean there's memory leak).

Take a heap snapshot, press test and take a heap snapshot. If you want the actual result you have to switch the view from "Summary" to "Comparaison". If the view is empty (in your case when I tested), it means nothing was added during the step, which mean that it doesn't have memory leak. In the other case, it will show you what was added or deleted between the snapshot.

Note : This method won't help you with memory leak for older browser that have their own issue, but it's a good step to find thing that will cause memory leak in most modern browser.

like image 35
HoLyVieR Avatar answered Sep 22 '22 10:09

HoLyVieR