I'm confused about this since I've seen several different comments. I'm reading a javascript book where it mentions that setting global variables to null is good practice (assuming there are no other references) and the GC reclaims memory for this variable on it's next sweep. I've seen other comments that say global variables are never disposed by the GC.
Also when programming javascript in a OOP structure, what happens if I have something like this (where game is in the global context):
var game = {};
game.level = 0;
game.hero = new hero();
//do stuff
game.hero = null;
Since hero lives inside an object which is stored in game, which is in a global context, If I set for instance hero to null, would this be disposed by the GC?
In JavaScript, the root is the global object. Periodically, the garbage collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.
An object is said to be "garbage", or collectible if there are zero references pointing to it. There is a limitation when it comes to circular references. In the following example, two objects are created with properties that reference one another, thus creating a cycle.
Garbage collection is a process that is implemented automatically. It can’t be forced or prevented anyhow. Objects can be retained in memory while they are reachable. It’s essential to know that being referenced is not similar to being reachable. Advanced algorithms of garbage collection are performed by modern engines.
This process of visiting and marking goes on and one until every reachable reference is visited. When this situation happens, the garbage collector knows which objects are marked and which are not. Those objects that are not marked are considered unreachable, and safe to be removed.
Global variables are never disposed of by the GC in the sense that a global variable will still exist. Setting it to null
will allow the memory that it references to be collected, however.
E.g.
Before:
global -> {nothingness}
After:
global -> var a -> object { foo: "bar" }
Set a
to null
:
global -> var a -> null
Here, the memory used by the object will be eligible for collection. The variable a
still exists though, and it simply references null
.
The statement that global variables are never collected is slightly misleading. It might be more accurate to say that any memory that is traceable back to the global context is not currently eligible for collection.
In answer to your question, yes - the hero object will be eligible for collection, because its indirect connection to the global context has been severed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With