The Primary Concept
- Local variables and the current function parameters.
- Parameters and variables for other functions on the nested calls’ current chain.
- Global variables.
The values above are called the roots.
Other values are known as reachable once they are reachable from a root by a chain of references or a single reference.
Consider an object inside a local variable. If that object has a property that references another object, that object is called reachable. The references are also reachable.
For a better perception, check out the example below:
As you can see, the object reference is depicted by the arrow. The global variable "book" is referencing the object. The "name" property itself stores a primitive.
In case the book value is overwritten, the reference will be lost, as shown below:
So, the object becomes unreachable. The garbage collector junks the data, freeing the memory.
A Case of Two References
In this section, let’ consider that the reference was copied from the book to language like this:
Now, doing the same will look like this:
The object will still be reachable via the language global variable. It’s in the memory. After overwriting the language, it can be deleted.
The main algorithm of the garbage collection is known as “mark-and-sweep”. Regularly some garbage collection steps are performed. Here they are:
- The collector takes roots and marks, remembering them.
- Afterward, it visits and marks all the references from them.
- The next step is visiting the marked objects, marking their references. It is not possible to visit the same object twice, as all the visited objects are remembered.
- The process goes on until every reachable reference is visited.
- All the objects except for the market objects are deleted.
And, finally, the objects that couldn’t be visited during the process above, are considered unreachable and are going to be removed.
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.