AngularInDepth is moving away from Medium. More recent articles are hosted on the new platform inDepth.dev. Thanks for being part of indepth movement!

Performance is crucial to the success of a web application. As a developer, it’s essential to know how memory leaks are created and how to deal with them.

This knowledge is especially important once your application reaches a certain size. If you aren’t careful about memory leaks, then you may end up in a “memory-leak taskforce”. (Yes, I have also been part of one 😉).

Memory leaks can have multiple sources. However, we believe that in Angular, there’s a pattern to the most common cause of memory leaks. And, there’s also a way to avoid them.

What is memory management

In JavaScript memory is managed automatically. This memory life cycle usually consists of three steps:

Allocate the needed memory Read and write the allocated memory Release the memory as soon as it’s not needed anymore.

“This automaticity is a potential source of confusion: it can give developers the false impression that they don’t need to worry about memory management.” (mozilla.org)

If you don’t worry about memory management at all, there’s a chance you might run into a memory leak once your application reaches a certain size.

In essence, memory leaks can be defined as memory that is not required anymore but not released. In other words, some objects are not garbage collected.

How does garbage collection work? 🚛

A garbage collection removes garbage. Its job is to clean up memory that is not needed anymore. To determine which memory is required, the garbage collector uses a “mark and sweep” algorithm. As the name suggests, this algorithm consists of two phases, a mark phase and a sweep phase.

Mark phase