Mark As Completed Discussion

Garbage Collection

Garbage collection is the process of automatically freeing up memory on the heap that is no longer accessible by the application. It is essential for avoiding memory leaks and freeing up space for new memory allocations.

Without garbage collection, memory used by unused objects and data would never be reclaimed. Over time, the application would accumulate memory it can no longer access, leading to slower performance, lag, and eventual crashing.

For example:

JAVASCRIPT
1let obj = {
2  name: 'John'
3}; 
4
5// Memory allocated on heap for obj
6
7obj = null;
8
9// obj is no longer accessible 
10// Garbage collector can free obj's memory

The main strategies used for garbage collection in JavaScript are:

Reference counting

This technique counts the number of references to each object on the heap. When an object's reference count reaches zero, meaning it is no longer accessible, the garbage collector can free the memory allocated to that object.

JAVASCRIPT
1let obj1 = {
2  name: 'John'  
3};
4
5let obj2 = obj1; // obj1 now has 2 references
6
7obj2 = null; // obj1 has 1 reference 
8
9obj1 = null; // obj1 has 0 references and can be collected

Mark and sweep

The heap is iteratively scanned for accessible objects which are marked. Unmarked objects are deemed inaccessible and swept away, freeing memory.

Generational collection

The heap is divided into two generations - young and old. The young generation stores short-lived objects and is garbage collected more frequently.

Understanding how garbage collection works in JavaScript enables writing optimized code that best leverages memory.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment