Regardless of the programming language, the memory life cycle is the same for all programming languages. These are
- Allocating memory needed
- Using the allocated memory
- Free the allocated memory if it is no longer in use
Allocation of memory
Using the allocated memory means reading, writing in allocated memory, i.e., using variables or objects for different purposes in our code.
Freeing Allocated memory
These algorithms are
- Reference-counting garbage collection
- Mark-and-sweep algorithm
Reference-counting garbage collection
It is a naive garbage collection algorithm. This algorithm looks for those objects which have no reference left. An object becomes part of garbage collection if it has no references attached to it, i.e., it is unreachable.
Let’s visualize this through an example.
The garbage collection algorithm fails in the case of circular references. Let’s visualize this through an example.
Here, the reference-counting algorithm does not remove obj1 and obj2 from memory after the function call. Both the objects are referenced by each other, resulting in neither of them marked for garbage collection.
This algorithm starts from the root object and finds all objects that can be reached from this root, all objects referenced from these, etc. The garbage collector will thus find all reachable objects and collect all non-reachable objects from the root. So all the objects that were unreachable to the root, initiating as garbage collection, and later the memory is freed removing those objects. Let’s understand this by looking at the following instance.
Created object obj1 becomes reachable from the root.
|obj1 = null;|
After setting the value of obj1 to null, the object is no longer reachable from the root object, and hence it is garbage collected.
The limitation of circular reference is not observed here as after the function call; the two objects are no longer referenced by any object that is reachable from the root object. So, they will be marked as unreachable by the garbage collector.
It is an automated process to find unreachable objects that are removed from the memory.
There are mainly two types of primitive values(which include boolean, null, undefined, number, BigInt, Symbol type) and objects.
- What is the memory life cycle?
The process of allocating memory, using the allocated memory, and freeing it if not needed, is called the memory life cycle.
- What is circular referencing?
Circular referencing is a series of references where an object references itself directly or indirectly through a series of objects, resulting in a closed-loop.