Javascript-Garbage Collection
Garbage collection is the process of finding a memory, that has no longer used by the application and releasing it. To find the memory collection which is no longer used, a few algorithms will be provided by the garbage collector, and in this section, we will look into the main garbage collection algorithms and their limitations. We will look into the following algorithms:
- Reference-counting garbage collection.
- Mark-and-sweep algorithm.
Reference-Counting Garbage Collection:
This is the most important garbage collection algorithm. If in these algorithms, there are no references to an object, it will be automatically garbage collected. This algorithm considers the zero(0) referencing object as an object that is no longer used by the application.
Example:
var o = { a : { b : 2 }};
// 2 objects created. One is referenced by the other as one of its properties.
// Obviously, none can be garbage-collected
o = 1; // what was the 'a' property of the object originally in o
// has zero references to it. It can be garbage collected.
Limitation: Cycles
function func() {
var o = {};
var o2 = {};
o.a = o2; // o references o2
o2 = o; // o2 references o
return 'true';
}
func();
The above code snippet in which o is referenced to o2 and o2 is referenced to o and it uses a cycle.
Mark-and-Sweep Algorithm:
The garbage collector provides this algorithm to free memory when an object is unreachable, rather than a zero(0) referencing object.
It will be first to find all the global or root objects and will find all the references to these global objects and references to the reference object, and so on. Using this algorithm for the garbage collector will identify the reachable objects and unreachable objects(automatically garbage collected.).
