Buildtide
Author: Hussain Mir Ali

I am interested in web and mobile technologies.

If you have any questions or feedback then message me at devtips@Buildtide.com.

Memory Management in JavaScript Part-2

The modern web browsers are shipping with a 'Mark and Sweep' based garbage collector. Although there have been improvements to the 'Mark and Sweep' algorithm like 'generational memory management' for the V8 engine in Chrome but I have only discussed the base algorithm in this post.


The Mark and Sweep Algorithm:


Fig 1.0 Visualizing Mark and Sweep Algorithm 

The 'Mark and Sweep' algorithm consists of two phases. The first phase is responsible for collecting information on 'reachable' objects, this phase is called 'mark' phase. The second phase is responsible for freeing up space for 'un-reachable' objects, this phase is called 'sweep' phase.

Mark Phase:

The 'Mark and Sweep' algorithm periodically traverses through the list of variables in the target JavaScript environment. While traversing it marks values that are referred to by the variables its traversing. If the referenced values are objects themselves(Arrays or Object literals) the algorithm recursively marks  each of the contained values in them as 'reachable'. At the same time it collects all the values that have not been referenced by any other variable. In Fig 1.0 I have visualized a high level overview of the 'mark' phase of the algorithm. For the case when the algorithm traverses through 'object 1' it then recursively traverses through other objects in the list and marks them. This is because the other objects in the list were referred to by 'object 1'.

Sweep Phase:

After the algorithm has completed the 'mark' phase it then starts the 'sweep' phase. It starts by traversing through all variables in target environment again. But now if any value is not marked it de-allocates memory for that value. 

In the base algorithm the 'sweep' phase will occur right after the 'mark' phase. This might affect the speed of the application and can slow it down. But recent improvements like 'generational memory management' to the base algorithm promises to remove this overhead.