mzu
mzu

Reputation: 759

Firefox console.log preventing JavaScript String from getting garbage collected?

With the following code whenever console.log is enabled the String referenced by o.big will not get garbage collected. As soon as I remove the logging statement the memory for the big String gets freed after the execution of the handler function finishes.

I am using Firefox 9.0.1 and the memory profiling was done with about:memory.

$(function() {  
    var handler = function() {  
      var o = {};  
      o.big = (new Array(20*1024*1024)).join("x");  
      console.log(o.big);  
      delete o.big;  
    };  

    $("#btn").click(handler);
});

I am fairly new to JavaScript and it would be great if someone could point out to me why the String does not get marked by gc if used within console.log.

Upvotes: 1

Views: 738

Answers (2)

user123444555621
user123444555621

Reputation: 153184

Not sure if Firefox keeps a reference to the original string there. I'd argue that console.log() retains a copy, since strings are first-class members in JS.

You can see the string-chars memory usage dropping in about:memory, but heap-unclassified rising. This may be related to https://bugzilla.mozilla.org/show_bug.cgi?id=563700, or it may mean that FF's GC is broken.

Upvotes: 0

NobRuked
NobRuked

Reputation: 593

Although I'm not too familiar with Firefox's / Firebug's handling of console.log() I assume that the console showing the "logged" object provides a way of examining and interacting with it. This is at least the case for Chrome.

Therefore, the console needs a reference to the object which will be kept in memory and cannot be garbage collected until the console releases the reference (which may not happen until the page hosting the script is reloaded).

Finally, keep in mind that there is no explicit relationship between the delete operator and garbage collection.

Upvotes: 2

Related Questions