Angular & RxJS: Detecting Memory Leaks
Tags: angular, rxjs, webdev, chrome
Published: 2019-05-29 23:00:40

---
title: Angular & RxJS: Detecting Memory Leaks
published: true
tags: angular,rxjs,webdev,chrome
canonical_url: https://itnext.io/angular-rxjs-detecting-memory-leaks-bdd312a070a0
---

I’ve built a sample Angular application using RxJS to simulate various memory leaks. The majority of these techniques apply to any component-based framework using RxJS.

You can download the source code here: [**https://github.com/Everduin94/memory-leaks-rxjs**](https://github.com/Everduin94/memory-leaks-rxjs) 🚀

We’ll cover:

1. Strategies for detecting a memory leak
2. Unsubscribe and Garbage Collection
3. Solutions to resolve subscription-based memory leaks

### Strategies For Detecting A Memory Leak

Using Google Chrome Developer Tools 🛠 (Ctrl+Shift+I) In Google Chrome

![](https://cdn-images-1.medium.com/max/642/1*Vdpx6qWXaG8Vgr612FlMSg.png)

#### **Allocation Timeline 📈**

Allocation Timelines allow us to see if the minimum size of our heap is growing over time. We’ll start with a baseline before creating or destroying any components.

![](https://cdn-images-1.medium.com/max/789/1*1wJuyDE4eSxijssxdP8UKg.png)

Now while the timeline is running, we’ll create/destroy the LargeLeak Component multiple times. Note, I’ve typed large into the filter as we are looking for allocations of the LargeLeakComponent

![](https://cdn-images-1.medium.com/max/1024/1*llr0aXPbsxkingnCbJ_WSg.png)<figcaption>LargeLeakComponent.ts</figcaption>

![](https://cdn-images-1.medium.com/max/792/1*BO3vR8RBXPWLFV0qjTsf9g.png)

Now we return to our starting point (destroy LargeLeakComponent) → manually run garbage collection (🗑 garbage-can icon in the top left) → and restart the allocation timeline (⚫ circle icon in the top left). We can see our minimum heap size has increased and the allocations are not being released.

![](https://cdn-images-1.medium.com/max/782/1*nBu2ckm9fsFgEgDTOfuEZw.png)

#### **Heap Snapshot 📸**

The heap snapshot is useful once we’ve identified a leak. Unlike allocation timelines 🐌, a heap snapshot won’t cause latency while we interact with our app. Ultimately, both snapshot and allocation timeline can be used to detect leaks.

We’ll start with a heap snapshot before doing anything in our application. This will be our baseline or starting point. We can see 0 ServiceObservableLeak Components have been allocated.

![](https://cdn-images-1.medium.com/max/1024/1*oZswZXkVnYbHLQEfKK417w.png)<figcaption>ServiceObservableLeak.ts</figcaption>

![](https://cdn-images-1.medium.com/max/787/1*Adn3R1c5QUmygfjhN1F_uA.png)

After toggling creation/destruction multiple times → manually running garbage collection 🗑→ and taking another snapshot ⚫. We can see that the component is not being released via garbage collection.

![](https://cdn-images-1.medium.com/max/798/1*JwsguLButwYr3KpMpymzsQ.png)

Note, searching for just the component is not always an effective method for finding a memory leak. If we assume there is a memory leak, we should also inspect the number of subscribers in memory. 🔍 Using the snapshot comparison (Dropdown next to filter), we can compare two separate snapshots. This shows us we’ve allocated 30 subscribers and deleted 0. More on this in “Unsubscribe and Garbage Collection”.

![](https://cdn-images-1.medium.com/max/910/1*DCa53K2eFIaHJL9f5d8Abw.png)

### **Unsubscribe and Garbage Collection**

It’s commonly mentioned that subscriptions hold a reference to the component. Thus, the component cannot be released, creating a memory leak. Not being able to release either object referencing each other is known as a cycle. [[1]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management)

Cycles are a limitation of the “Reference-counting garbage collection” algorithm. Modern browsers utilize a “Mark-and-sweep” algorithm 🎯. Mark and Sweep algorithms will collect all non-reachable objects from the root (Global Object). This solves the limitations of cycles.

We can validate this idea of cycles being handled by the garbage collector by testing with a local finite observable. As we toggle the local-finite component → manually run garbage collection 🗑→ take a heap snapshot ⚫.

![](https://cdn-images-1.medium.com/max/1024/1*OlBEXQdubKn1SVmEJvKYRQ.png)<figcaption>FiniteObservableComponent.ts</figcaption>

![](https://cdn-images-1.medium.com/max/797/1*k0xqb0-41cnJzSwIBoxksQ.png)

We can see that the component is not leaking, even though we have not used a subscription management strategy (such as unsubscribe).

> _”So I can just let garbage collection manage my subscriptions?”_

**No.**

![](https://thepracticaldev.s3.amazonaws.com/i/noiqrwv2m5su9mayim7p.gif)

If the subscription/component still has some reference back to the root, it will not be garbage collected. We can see this in our ServiceObservableLeak Component from the previous example. Since our observable (observable$) is allocated in a service (SourceService), the component still has a reference back to the root via the observable. We need to unsubscribe for the component (ServiceObservableLeakComponent) to be available for garbage collection.

![](https://cdn-images-1.medium.com/max/726/1*B_TxSruza9lrfFtZLPdjBw.png)

Not managing subscriptions is a bad practice and should be avoided. Take the FromEvent Component for example. The component initializes a local observable that is watching for click events on a button within FromEventComponent.

![](https://cdn-images-1.medium.com/max/1024/1*kFLR2OrVSsqrc6z5SpWHJQ.png)<figcaption>FromEventComponent.ts</figcaption>

![](https://cdn-images-1.medium.com/max/919/1*Nh5DWQ0OtThb0EiUD6_2mg.png)

In this example, the component is being released but the subscriber is not. To make the situation more complicated, the subscriber only leaks when the click event has been fired at least once. This creates a memory leak that is very difficult to track down. — The solution is to always manage your subscriptions.

### **Solutions**

![](https://thepracticaldev.s3.amazonaws.com/i/q25altwpke5zxqse3xmf.gif)

I plan to write in more detail on these methods in a future article. For now, here’s a high-level overview. 🌎

#### Unsubscribe

Unsubscribing to all subscriptions in the ngOnDestroy method is a valid strategy. This is similar to what the async pipe does under the hood on a component-level.

![](https://cdn-images-1.medium.com/max/1024/1*ePafZp5DswpHRrjgxZM-lw.png)

#### Async Pipe

Will manage your subscription based on the life of the DOM element it’s associated with. Async pipe will make a new subscription wherever it’s declared. Use “as” to re-use the value provided.

![](https://cdn-images-1.medium.com/max/1024/1*h_gZJTcdaB39ejXkRQZnxQ.png)

#### Take

take, takeUntil, and takeWhile will all manage a subscription automatically based on a condition being met. For example, takeUntil will take an observable as an argument and maintain a subscription until that observable emits a value.

![](https://cdn-images-1.medium.com/max/1024/1*6_XXCKo_cdGswxhwNyf55w.png)

* * *

### **Resources / References**

- [1]: [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory\_Management](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management)
- Syntax-highlighted images are generated by [https://carbon.now.sh](https://carbon.now.sh/)