Do You Write Better JavaScript?

Being a Performance Conscious Developer

Harsha Vardhan
Nov 22, 2020 · 4 min read
Image for post
Image for post
Photo by krakenimages on Unsplash

Being a developer, it is essential to worry about the performance of the application that we build. Memory management is one of the major factors that affects the performance of an application. Many a time JavaScript developers tend to not consciously think about memory management because JavaScript automatically allocates memory space when an object is created and collects them later as garbage when they’re not used. These behind the scenes behaviour of garbage collection in JavaScript could cause a lot of confusion. Read further to understand this better.

Memory Life Cycle

There are three steps involved in the memory life cycle of almost all programming languages:

  1. Allocate the memory you need
  2. Use the allocated memory (read, write)
  3. Release the allocated memory when it is no longer needed

If the developers don’t understand how these steps work, they are susceptible to code poorly and thus causing Memory leaks. Memory leak is a condition where memory does not get released even when the object is not needed anymore.

Let’s look into each of these steps closely.

Allocation of memory in JavaScript

Memory is allocated in the following scenarios:

  • When values are initialized
let num = 123;
let st = 'abc';
let arr = [1,2,3];
  • Using function calls.
let date = new Date(); // creates a Date object and allocates memory
let element = document.createElement(‘div’);
// allocates a DOM element

Using the allocated memory

Whenever any of these values are being read or written then the memory gets used. These values could mean any variable, function or even an object passed to a function.

Release the allocated memory

Most of the low level languages have methods to manually allocate or release memory, like in C we have malloc() and free(). But, in JavaScript it happens automatically using a mechanism called Garbage collection (GC). A garbage collector does the three steps involved in the memory life cycle all by itself. The problem here occurs when GC tries to estimate if a memory is no longer needed or not.

Garbage Collection

One of the basic concepts that each of the garbage collection algorithms use is Reference. If any object has access to another object, then that can be called as reference.

The following are few of the algorithms used for Garbage collection:

1. Reference-counting garbage collection

This is one of the simplest and basic algorithms that just counts the number of references associated with any object. If an object has no reference at all, then it is collected as garbage. One of the most common usage of this algorithm is in IE 6 and IE 7 where this algorithm is used for DOM objects.

let a = {
b: {
c: 'Harsha'
}
};
// 2 objects are created. One is referenced by the other as one of // its properties.// The other is referenced by virtue of being assigned to the // variable 'a'.let z = a.b; // Reference to ‘b’ property of the object.// This object now has 2 references: one as a property,
// the other as the ‘z’ variable.
a = 'HarshaVardhan'; //The object initially had json and now it has // lost all references and it’s garbage collectedz = null; // The ‘b’ property of the object originally in a has zero // references to it. It can be garbage collected.

There is a known limitation in this algorithm — Circular references. A circular reference occurs when two objects are created with reference to each other and it creates a cycle. Since there will always be one reference to each of the objects, it will never be garbage collected thus causing a Memory leak.

function CircularRef() {
let obj_1 = {};
let obj_2 = {};

// obj_1 references obj_2
obj_1.object = obj_2;
// obj_2 references obj_1
obj_2.object = obj_1;
return ‘Memory leak’;
}
CircularRef();

2. Mark-and-sweep-algorithm

This algorithm simplifies the problem by considering only the reachability of any object. In this algorithm the garbage collector starts with the global objects (aka ‘roots’) and then marks reachable and unreachable objects accordingly. Here, the circular reference is no longer a problem. Most of the modern browsers use this algorithm. Only limitation that we’re left with now is, there’s no way we can manually release any memory like in C.

Conclusion

Understanding how memory is managed is crucial because it gives a better understanding as to how JavaScript works and helps you code better without worrying about the performance of your application.

Did you enjoy this article? If so, get more similar content by subscribing to Decoded, our YouTube channel!

May the GC be with you :)

Reference

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store