Memory clearing is a mandatory process for any application, including those written in JS. If we neglect this process, the memory will be filled with objects (mostly “dead” ones), and at some point, there will simply be no place for new data. In this article, we will analyze the basic principles of clearing memory in JS, as well as consider several garbage collection algorithms and determine which one is more efficient.

What Garbage Is

Garbage is any object that cannot be reached by reference from the “root”. Garbage includes all “dead objects” that have lost contact with the root ones.

Moreover, “dead” objects can often be linked with each other and form chains of considerable dimensions. Still, it doesn’t make them “live,” and that’s why a reference counting approach to garbage collection doesn’t work. But which ones work then? Let’s start at the beginning.

Approaches to Garbage Collection

Let’s consider several approaches, starting with the simplest and fastest and ending with the most effective but slowest ones.

Mark and Sweep

This is the easiest garbage search and deletion algorithm. It works only in a situation where the memory contains garbage; if it is only filled with live objects, Mark and Sweep doesn’t do anything.

The main drawback of Mark and Sweep is that it fragments memory. As a result, it can clear a lot of space, but still, a new large object can’t be stored in RAM.

#javascript #web-development #programming #developer

Garbage Collectors in JavaScript
2.55 GEEK