Memory management in JavaScript
JavaScript as a language does not perform Garbage collection but this task is handled by browser. Whenever a webpage has some stuck-up effect, the reason behind is the browser performing Garbage collection behind the scene.
Since garbage collection in JavaScript is implicit and the algorithm for same is categorized as undecidable problem , we can write our code in optimized way to perform optimized memory management. Some of the ways which can help in memory management in JavaScript are listed below:
Reuse objects as much as possible: Changing the properties of same object instead of allocating a new object helps in reducing the garbage collection time
Reuse existing arrays: Emptying an array by assigning it to [] creates a new array instead of emptying existing one. To reuse an array, use array.length = 0 instead.
Reuse existing function: Functions which are being called again and again can be allocated memory by assigning to variable and then using the variable. E.g.:
setInterval(function(){ alert("a");}, 1000);
can be rewritten as
var func = function(){ alert("a");};
setInterval(func, 1000);
Garbage Collection:. As already mentioned, the problem to decide for garbage collection is categorized as undecidable problem, there are some constraints imposed to implement the same in browsers, as explained below:
References: An object is said to reference other object if former has access to latter either explicitly or implicitly(via prototypes)
Reference-counting garbage collection: This is the most naive Garbage collection algorithm and states that an object is garbage collectable if there are no objects referencing it. E.g
// object 'obj' created with 1 attribute
var obj = { a: 'value1' };
// 'obj2' refers 'obj'. Hence 'obj' cannot be Garbage collected yet
var obj2 = obj; obj = 0;
// 'obja' has reference to attribute 'a' of 'obj'
var obja = obj.a;
// here 'obj' can be garbage collected but since 'obja' still has reference to 'obj.a', garbage collection cannot be done on 'obj'
obj2 = null;
// Now 'obj' becomes a candidate for garbage collection
obja = null;















