Memory management is one of the key aspects of any programming language .In some of the low level programming languages like C, it is done manually using malloc and calloc and free while in high level programming language like javascript ,it is done automatically(garbage collection).
The key concept of garbage collection is Reachability. By Reachability I mean till the time the variables are used in a program it will not be destroyed. Once the variable is no more in use or it is not reachable ,it will be destroyed.
Before understanding Reachability, let's understand the phases of memory management. There are three phases involved in memory management Allocation phase :In this phase the memory is allocated to the declared variable and functions. Utilization phase : In this phase the value processing is done (reading or writing) Release phase : Once the processing is done a memory is no longer required.
Now let us see what Reachability is. Example 1:
let x = {
a: {
b: "c",
},
};
There are two objects created. a is referenced by x property and b is referenced as a's property. Now,
let y = x; /* reference the object copied to y.*/
x = 1 /* x is reassigned hence the reference
of the object with x is lost.*/
let z = x.a /* z has the reference of object
referenced by a */
y = 2; // reference of object with y is also lost.
z = null; /* when z is reassigned the reference
of a is also lost and a becomes unreachable,
hence it will be garbage collected.*/
Example 2 : Circular Reference
let x = {};
let y = {};
x.a = y;
y.b = x;
Here the property of x is referencing b and vice versa. This creates a circular reference and memory for x and y will never be released.This is one of the major causes of memory leakage.
Summary :
- Reference is the key concept of garbage collection.
- As long as the object has reference it will not be garbage collected.
- Circular Reference is one of the major causes of memory leak.
That’s it and if you found this article helpful, please give a like, you can also follow me on LinkedIn ,if you have any doubt, feel free to comment! I’d be happy to help :)