Fix Memory Leaks in JavaScript

Vishnu Sasidharan
JavaScript in Plain English
5 min readNov 6, 2020

--

Memory costs

Memory leak is referred to a scenario where the memory used by the application is not released even after use. This could cause the operating system to allocate way more memory to the application than required. In the presence of a memory leak the memory allocation is progressive. This memory consumption by the application will keep increasing until the operating system runs out of it.

Imagine you invite some guests over for dinner and they take your beautiful ceramic plate and refuse to let it go after dinner. And then very graciously go on and take more until they have it all. That’s basically memory leak. Let’s see what is so different about memory leaks in JavaScript.

Memory Management in JavaScript

Generally memory management has 3 processes:
1. Allocation
2. Usage
3. Collection/Release

Every object/variable that you create goes through these 3 stages. Here we are concerned about the last process: Collection/Release. In JavaScript, this process is implicit and is called garbage collection.

Unfortunately, this convenience makes us overlook the memory usage of our application and results in web applications that uses much more memory than it really should. Even worse, this makes memory leak more likely to occur within even the simplest applications.

So how do you identify a memory leak?

Identifying a Memory Leak

  1. Preliminary test for memory leak:
    When you navigate to a page in a web application and the performance degrades progressively over a period of time, it could be an indication of a memory leak. However its not conclusive, since it is only a sign of heavy resource consumption, it could be poor network or heavy CPU consumption too.
  2. Secondary test for memory leak:
    You can simple open task manager within chrome and watch for the memory footprint there for this particular tab. If it keeps increasing, there is a high chance that there is a memory leak.
  3. Conclusive test for memory leak:
    The first two tests, although effective, can only detect medium to severe memory leaks. Sometimes memory leaks are really small and only show their effects over long periods of time. This method can detect even the smallest memory leak. Hence, this is the recommended method to make sure your guests don’t take all your plates. This involves using the performance feature of Chrome inspector.

1. Visualizing Leak Using Performance

The following are the steps to record the performance:
1. Open Chrome inspector and navigate to Performance tab.
2. Make sure the Memory Checkbox is checked.
3. Click the record button.
4. Perform the action that you suspect is causing the memory leak.
5. Wait for a certain period of time (30–60 seconds)and stop recording.

Now its time to inspect the memory graph. You will see many graphs on the screen. You need to look for the blue graph shown below:

Normal JS Heap Performance

The blue staircase graph in the picture above is your JS Heap. Normally when a page loads, you would expect an increase in memory as objects are being allocated and a dip(marked with orange circle) which happens at garbage collection. As the page is completely loaded, you would see an equilibrium is reached in terms of memory consumption. The graph will oscillate between this maximum and a minimum point over time. If your graph something like this, your app has no memory leaks. Hurrah! Let’s take a look at a memory leak case:

Memory Leak

This staircase graph of JS Heap is a clear indication that there is a memory leak in your application. Here again, the dip signifies garbage collection, however, in this case the memory allocation keeps increasing over time. Eventually, the page performance will degrade significantly. This confirms that your app has a memory leak.

Sometimes, the graph isn’t so clear. In this case, you need to record the performance longer to see the trend over the long run. Now that we know we have a memory leak, time to fix it.

2. Fixing The Leak

“Debugging is a crime scene where you are the detective, the victim and the criminal”

We need to start with identifying the suspects causing the memory leak. The memory tab in Chrome Inspector will help us to do exactly this.

Click on the memory tab. Here you have three options to take a memory snapshot:

  1. JS Heap Snapshot: Shows memory distribution of JS objects and DOM elements.
  2. Allocation Instrumentation on Timeline: Shows JS object memory allocation during a specific time interval. This is used to isolate memory leaks.
  3. Allocation Sampling: Breaks down memory allocation by JS execution tasks. Has the least amount of performance overhead.

Here we are primarily concerned with JS Heap Snapshot and Allocation Sampling. You can Select each of them and record a snapshot.

JS Heap Snapshot

JS Snapshot of a page

Here you can see which DOM element is taking the most amount of memory. That way you can isolate a memory leak suspect and investigate further. As you can see in the image, we have objects listed and distance, shallow size as well as retained size.

Distance is the length of the element from the root node in the DOM. Shallow size refers to the size of the object itself i.e array, JS objects, variables etc. The retained size is the size that can be retained after the object is deleted. This can narrow down you search for your suspect significantly if the suspect is a recurring DOM element or an ever increasing JS object.

Allocation Sampling

Allocation Sampling example

In Allocation sampling, you can see the memory distribution based on individual functions. You can sort it by heavy at the top and this can list you the functions taking up the most amount of memory. Once you know the function name, you can investigate the code snippet that the function belongs to and find out what is causing the leak.

Conclusion

These are a very effective way to debug memory leaks and can resolve most of significant memory leaks in a web application. It’s time to take your ceramic plates back!

If this post was helpful, follow me on Medium, I write code and tell stories. Cheers!

--

--