Memory management in JavaScript

Introduction

The purpose of memory management is to provide dynamically allocated memory when requested for and later free that memory containing objects if that is no longer needed. Languages like C, C++ have primitive functions for memory management like malloc(), calloc(), free(), where some high-level languages like JavaScript include a garbage collector to do this job. It tracks the memory allocation, and if the allocated memory is no longer used, it frees automatically. But algorithms for garbage collection cannot completely decide if the memory is required or not. Therefore, the programmer needs to understand and decide if a particular piece of code needs memory or not.

 

Memory Life Cycle in javascript

Regardless of the programming language, the memory life cycle is the same for all programming languages. These are

 

  • Allocating memory needed
  • Using the allocated memory
  • Free the allocated memory if it is no longer in use

 

Using allocated memory is done explicitly, but allocation and freeing memory is implicit for javascript.

 

Allocation of memory

In javascript, memory allocation is done mainly in two ways. Go through the code snippet to understand these allocation methods.

 

By initialization

var n = 3; // allocates memory for a number
var s = 'string'; // allocates memory for a string

var obj = {
  a: 1,
  b: null
}; // allocates memory for an object

var a = [2,'text',5]; // allocates memory for an array

function fun(x) {
  return x;
} // allocates a function,callable object



// function expressions also allocate an object
someElement.addEventListener('click', () =>{
  someElement.style.backgroundColor = 'blue';
}, false);
Allocation by function calls

var d = new Date(); // a Date object allocated

var elm = document.createElement('div'); // allocates a DOM element
var s1 = 'string';
var s2 = s1.substr(0, 4); // s2 is a new string
                        //  to store the [0, 4] range of s1.

 

Using the allocated memory means reading, writing in allocated memory, i.e., using variables or objects for different purposes in our code.

 

Freeing Allocated memory

Most memory management issues occur, freeing allocated memory when the allocated memory is no longer needed as javascript uses a form of automatic memory management known as garbage collection. This automated process is an approximation as determining whether or not a specific piece of memory is still needed is undecidable.

 

Garbage collection

The JavaScript Engine’s garbage collector uses two garbage collection algorithms to find unreachable objects removed from the memory.

These algorithms are

  • Reference-counting garbage collection
  • Mark-and-sweep algorithm

 

Reference-counting garbage collection

It is a naive garbage collection algorithm. This algorithm looks for those objects which have no reference left. An object becomes part of garbage collection if it has no references attached to it, i.e., it is unreachable.

 

Let’s visualize this through an example.

 

var obj1 = {
  a: {
      b: 10
  }
};
    // 2 objects are created. ‘a’ is referenced by obj1 as one of its properties.
  // So, none can be garbage-collected.

var obj2 = obj1;      // The 'obj2' variable is the second thing that has a reference to the object.

obj1= 1;          // the object that was originally in 'obj1' has a unique reference ob,j2
                      //   embodied by the 'obj2' variable.

var x = obj2.a;    // reference to 'a' property of the object.
                          //   This object now has 2 references:  //one as a property and the other as the 'x' variable.

obj2= 'text';  // The object that was originally in 'obj1' has now                     
                  //  zero references to it. So, it can be garbage-collected.
                //   However its 'a' property is still referenced                              //by   the 'x' variable, so its memory cannot be freed.

x = null;       // The 'a' property of the object originally in 
                // obj1  has zero references to it. It can be garbage collected.

 

Limitation

The garbage collection algorithm fails in the case of circular references. Let’s visualize this through an example.

 

function fun() {
    var obj1 = {
        property1 : {
            subproperty1: 10
        }
    };
    var obj2 = obj1.property1;
    obj2.property1 = obj1;
    return 'any text';
}
fun();

 

Here, the reference-counting algorithm does not remove obj1 and obj2 from memory after the function call. Both the objects are referenced by each other, resulting in neither of them marked for garbage collection.

 

Mark-and-sweep algorithm

This algorithm searches for the objects which are unreachable from the root, which is JavaScript’s global object. This algorithm overcomes the limitations of the Reference-counting algorithm. An object with no references would be unreachable, but instead of having reference, if it is unreachable from the root object, then the object is also part of garbage collection.

 

This algorithm starts from the root object and finds all objects that can be reached from this root, all objects referenced from these, etc. The garbage collector will thus find all reachable objects and collect all non-reachable objects from the root. So all the objects that were unreachable to the root, initiating as garbage collection, and later the memory is freed removing those objects. Let’s understand this by looking at the following instance.

 

var obj1 = {
    property1: 35
}

Source: medium

                           

Created object obj1 becomes reachable from the root.

 

obj1 null;

 

Source: medium

 

After setting the value of obj1 to null, the object is no longer reachable from the root object, and hence it is garbage collected.

 

The limitation of circular reference is not observed here as after the function call; the two objects are no longer referenced by any object that is reachable from the root object. So, they will be marked as unreachable by the garbage collector.

FAQs

  1. What is the garbage collector in JavaScript? 

    It is an automated process to find unreachable objects that are removed from the memory.
     
  2. What are data types in JavaScript? 

    There are mainly two types of primitive values(which include boolean, null, undefined, number, BigInt, Symbol type) and objects.
     
  3. What is the memory life cycle?
    The process of allocating memory, using the allocated memory, and freeing it if not needed, is called the memory life cycle.
     
  4. What is circular referencing?

    Circular referencing is a series of references where an object references itself directly or indirectly through a series of objects, resulting in a closed-loop.
     
  5. What is the global or root object in JavaScript?
     

The JavaScript Global Object is a globally defined object that has some properties and methods which are and are available to all objects or variables of a JavaScript program.

 

Key Takeaways

The blog covered memory management in JavaScript.

Now that you know the concept of memory management in JavaScript go ahead and practice questions based on them on our CodeStudio Platform.


Don't stop learning here. Check out our Basics of JavaScript - guided path to learn JavaScript from scratch. If you are preparing for JavaScript Interviews, check out the blog Javascript Interview Questions.

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think