How does the Javascript garbage collector work?

Asked

Viewed 328 times

14

Simple variables

Correct me if I’m wrong, but in Java the garbage collector eliminates objects that are no longer referenced:

Cliente cliente = new Cliente();
cliente = null; // o coletor de lixo cuidará disso

The same goes for Javascript?

var obj = {foo: "bar"};
obj = null; // isso foi limpo da memória?


Function

What is the condition for variables within functions to be eliminated? I know there are at least some conditions under which they need to be maintained:

var foo = (function() {
    var text = "bar";
    var bar = function() {
        alert(text);
    };

    return bar;
})();

In the above case the variable text needs to be maintained (I believe), as it is still being referenced by the returned function.


GIFT

Removed content is deleted from memory?

<div id="foo">
    <div id="bar">
        ...
    </div>
</div>
var foo = document.getElementById("foo");
foo.innerHTML = ""; // isso será limpo?

1 answer

15


It seems that you already understood well how it works, but I will comment on each case.

Simple variables

If there is no further reference to the object, he may be eliminated:

var obj = {foo: "bar"};
obj = null; // sim, isso foi limpo da memória

However:

var bar = {foo: "bar"};
var boo = bar;
bar = null; // bar não contém mais nada, mas o objeto ainda está em boo

That is, in the case of multiple references to the same object, all need to be nullified so that it is marked as garbage. In fact, important: the memory is not released at the exact moment when the reference is set to null. At this point, the value becomes "collectible", but the GC runs at the time the implementation deems it most opportune.

Function

You’re right, if a figure is captured in a closure, he cannot be released:

var foo = (function() {
    var text = "bar";
    var bar = function() {
        alert(text);
    };

    return bar;
})();

That is, the string "bar" will continue to exist while foo exist.

GIFT

Nowadays there is not much difference when dealing with DOM objects and common objects, The rules explained above apply in the same way. But in the past it was not the case. I remember excluding elements of the DOM without excluding its Event listeners, and later when inserting another node with the same ID as the one that had been removed, the Istener would resurrect! This if I’m not mistaken occurred not only in IE, but also in Firefox. But everything indicates that this kind of thing is really a problem of the past (like the classic circular references problem in the IE, which required a series of juggling to be avoided, up to IE8).

Reference Counting vs. Mark and Sweep

According to MDN, the GC of all modern browsers uses an algorithm of the type Mark and Sweep instead of Reference Counting. In Mark and Sweep, the collector traverses all living objects from a root (the global object, in this case), and considers "living" any object that can be referenced in this search. In practice, this means that memory can be released even if there is still some reference to the object to be cleaned, but this reference can no longer be accessed and used by the program. This solved the problem of circular references mentioned above.

  • 2

    I re-read the DOM part from references, and included a section on the types of GC.

  • Why references need to be nullified to be marked as garbage?

  • @FREEZE Because while there is some reference pointing to a certain object the garbage collector considers that this object is in use, and therefore cannot be removed from memory.

  • But it can’t be any value?

  • 1

    @FREEZE Yes, it can be another value. But usually there is no reason to recycle the variable, and put any value also occupies memory, which is what you want to avoid. Also, null traditionally carries the sense of absence of an object.

  • Um..., another question, using WeakMap can’t tell if an object has been removed from memory? { let obj = {}; var weak = new WeakMap; weak.set(obj, true); obj = null; }? When you run this on the console and see the value of weak, will probably log the property obj. If you wait a few minutes there won’t be any difference either. Weakmap was supposed to be here.

  • @Phanpy Not quite so, test that your code. If you have questions about Weak maps, post a question here on the site about this :)

  • I’m not sure... `At this point, the value becomes "collectible", but the GC runs at the time the implementation deems it most opportune.` (reference about Weakmap)[https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/WeakMap]

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.