Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Chrome's javascript garbage collection work differently? [duplicate]

When I try to debug this code (http://jsfiddle.net/QWFGN/)

var foo = (function(numb) {
    return {
        bar: function() {
            debugger;
            return "something";
        }
    }
})(1);
foo.bar()

Developer tool in Chrome behaves differently than and Firebug in Firefox and developer tool in IE. The issue is that variable numb is not visible in Chrome developer tool on the debugger; line. But, it is visible in Firebug and IE. If I try to type numb in Chrome's console I get:

ReferenceError: numb is not defined

numb, of course, is visible in this closure, and if I change code to (http://jsfiddle.net/QWFGN/1/)

var foo = (function(numb) {
    return {
        bar: function() {
            debugger;
            console.log(numb);
            return "something";
        }
    }
})(1);
foo.bar()

numb is now visible in Chrome as well and I can get value 1 as a response.

So, My question is: Why only Google Chrome doesn't see closure variables that are never used? Does Google Chrome have it's own implementation of Garbage Collection, or is it only related to implementation of debug tool in Google Chrome.

like image 784
dugokontov Avatar asked Mar 14 '13 13:03

dugokontov


People also ask

How does JavaScript garbage collection 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.

Does JavaScript use garbage collection?

In case of the low-level languages where the developer has to manually decide when the memory is no longer needed, high-level languages such as JavaScript use an automated form of memory management known as Garbage Collection(GC).

Does garbage collection affect performance?

The most common performance problem associated with Java™ relates to the garbage collection mechanism. If the size of the Java heap is too large, the heap must reside outside main memory. This causes increased paging activity, which affects Java performance.

How do I force garbage collection in JavaScript?

You can't force garbage collection (not in any sane fashion). If your variables aren't going out of scope automatically, just set them to null . Save this answer.


1 Answers

This doesn't have anything to do with garbage collection or the debug tools.

What's actually happening is that Chrome's JS engine realizes that you never use numb inside the function, so it doesn't include it in the closure at all.

Note that it can only do this if it can prove that the inner function never uses with or calls eval.

like image 194
SLaks Avatar answered Nov 13 '22 03:11

SLaks