Garbage Collection in JavaScript

Satyapriya Mishra
The Startup
Published in
5 min readFeb 16, 2021

--

We know what is a garbage. Garbage essentially refers to things which are no longer of use. When it comes to programming, Garbage Collection means cleaning the memory spaces which don’t contain useful data and then reallocating those cleared memory to some other data which is both active and useful. That is the basic process of Garbage Collection in pretty much all the programming languages in the world. Some programming languages needs explicit interference from the developer while some other languages do this automatically. A low level programming language like C, requires the developer to free the memory by the use of methods such as malloc() and free() when the program no longer needs those variables or objects.It is a developer prerogative to free the memory and the ball is in the developer’s court to decide explicitly whether to free the meory or not. But this is not always the case.For a high level programming language like JavaScript,
the memory management process is automated. The browser takes care of that thing for us.

In this section we will see the following contents.

  1. The memory management life cycle
  2. The Garbage Collection algorithms
  3. Pitfalls for memory leakage

Let us now see the general life cycle of memory management to better understand the process.

  • On the first step whenever a variable, object or function is created, a memory space is allocated to it.
  • In the next stage, the allocated memory is used by means of Read/Write operations.
  • When the memory is no longer needed, release the memory space.

The last step is called the Garbage Collection mechanism. This is an automated process in JavaScript and the process is done by an entity called Garbage Collector, though we can’t physically find this agent in the browser engine. The purpose of a Garbage Collector is to monitor memory allocation and determine if a specific memory is needed any longer. If it is not needed, then it reclaims the memory. But the Garbage Collection mechanism is always an approximation as the usefulness of a specific block of allocated memory is undecidable.

The Garbage Collection mechanism in JavaScript is governed by two algorithms which are listed below.

  1. Reference Counting Algorithm
  2. Mark and Sweep Algorithm

Let’s try to understand these one by one.

Reference Counting Algorithm
First of all let’s try to understand what is a reference.
Given two objects, one object is said to have a reference to another object if the first object has access to the methods or properties of the second object. Now let’s move on to the algorithm.
The Reference count algorithm is very simple and it determines the usefulness of an object by finding out if the object is being referenced by some other object or not. If the object is not referenced by any other object, then it is taken as a garbage value and collected. A simple example of this can be as follows.

var obj = { // first object created 
property1: { // second object created
property2 : 10
}
}

Here two objects are created and one is referenced by the property of the other object. The other object being referenced by being assigned to the obj variable. Since there is references, there is no scope of Garbage Collection.

var newObj = obj; // Now we have another to the existing objects.
obj = 10; // Still the objects are referenced by the newObj variable. So there is no chance of GC

Let’s see another implementation.

var anotherObj = newObj.property1;

Now the object property1 has two references. One as the property of the newObj variable and another from the anotherObj variable. So it can’t be garbage collected.

newObj = ‘Some string’;

Now the object created under obj variable has zero reference as such. But still its property1 is being referenced by the anotherObj variable. So it can’t be
garbage collected.

anotherObj = null;

Now we don’t have any reference to the property1 object from anywhere. Under this situation, the objects can be garbage collected.

The Reference Counting algorithm is very naïve in nature and it can’t be completely relied upon. For an example like below, the RC algorithm does very less.

function foo() {
var obj1 = {};
var obj2 = {};
obj1.a = obj2;
obj2.a = obj1;
console.log(obj1);
console.log(obj2);
}
foo();

Just traverse through the output objects. Can you see the nested a properties ? This is something known as a Circular Reference. In this case the Reference Counting algorithm fails miserably as all the nested objects are referenced by each other. So there is no possibility of garbage collection using this algorithm. This leads us to our next algorithm, i.e. the Mark and Sweep Algorithm.

Mark and Sweep Algorithm
The Mark and Sweep algorithm implements the GC mechanism by means of reaching out to objects. If the object is not reachable, then it is taken as a garbage and collected. The algorithm follows the principle that if an object is having zero references then it is effectively unreachable. So it is fit to be a garbage.
The process identifies the root object i.e. the window object and from there on it traverses to all other child objects and then to the children of the child objects. If there are some objects which can’t be reached in this process, they are collected as garbage and memory is freed. This algorithm effectively solves the cycle reference problem which we saw in the Reference Counting algorithm.

Some of the common pitfalls for memory leakage
A developer can do a lot to prevent memory leakage in his application. Some of the very common causes of memory leakage in the application is given below.

  1. Excessive use of globals by creating global variables or by omitting the var keyword in local scope
  2. Forgetting the clearing of timers like setInterval()
  3. Unnecessary use of closures (closures always keep a reference of the variables from the parent function even if the parent function has completed execution).

So we should always avoid doing the above mistakes.

This was a brief overview of the garbage collection process in JavaScript. The topic is very vast , but this can be a starting point to build knowledge further.

--

--