Garbage collection(GC) in JavaScript?

JavascriptFront End TechnologyObject Oriented Programming

garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program. The general problem of automatically finding whether some memory "is not needed anymore" is undecidable. As a consequence, garbage collectors implement a restriction of a solution to the general problem.

The main concept that garbage collection algorithms rely on is the concept of reference. Within the context of memory management, an object is said to reference another object if the former has access to the latter (either implicitly or explicitly).

Example

let a = []
function addToA() {
   let x = {name: "John"}
   a.push(x)
}
console.log(a[0])

Output

{name: "John"}

Note that x is not in scope anymore but is still accessible using a. This means that it needs to stay in memory until its reference is not there anymore. If we pop it from the array, it won't be needed anymore and can be garbage collected.

Garbage collectors work using following algorithms −

1. Reference-counting garbage collection − An object is said to be "garbage", or collectible if there are zero references pointing to it. This is used in older browsers. But this causes a problem with circular referencing objects as they cannot be collected(There is always a reference to them from the other object. )

2. Mark-and-sweep algorithm − This algorithm reduces the definition of "an object is no longer needed" to "an object is unreachable". This algorithm assumes the knowledge of a set of objects called roots. In JavaScript, the root is the global object. Periodically, the GC starts from these roots, find all objects that are referenced from these roots, recursively. Starting from the roots, the GC will thus find all reachable objects and collect all non-reachable objects.

You can read more about GC in javascript athttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management

raja
Published on 17-Sep-2019 08:00:35
Advertisements