How can circular references cause memory leakage in JavaScript?


Circular reference

 A circular reference is formed when two variables reference to each other there by giving each object a reference count of 1.In pure garbage collected system, a circular reference may not be a problem when the variables involved were have no references.In that scenario the declared variables will be garbage collected.In reference counting system neither of the objects will be destroyed,because the reference count cannot be zero.

In hybrid system, where reference counting and garbage collection are used, memory leaks will occur because the system fails to identify circular references.

Example

The following example shows a circular reference between javascript object and DOM object.The javascript object has a reference to DOM object(Div) and Dom object(Div), through "expando" property, has a reference to javascript object(obj). Since both objects were referenced to each other none can be destroyed there by causing memory leak.

<html>
<body>
<script>  
   window.onload = function(){
   var obj=document.getElementById("DivElement");
   document.getElementById("DivElement").expandoProperty=obj;
   obj.String=new Array(1000).join(new Array(2000);
   };
</script>
</body>
</html>

Avoiding memory leak

In the following example initially both javascript object and DOM object are in circular reference but when null is assigned to javascript object both the objects(javascript and DOM objects) will be in dilemma to figure out whom they are referencing that is whether javascript object is referencing null or the DOM object there by breaking circular reference. 

Example

<html>
<body>
<script>  
   window.onload = function(){
   var obj=document.getElementById("DivElement");
   document.getElementById("DivElement").expandoProperty=obj;
   obj.String=new Array(1000).join(new Array(2000);
   obj = null        // this breaks circular reference
   };
</script>
</body>
</html>

Updated on: 30-Jul-2019

374 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements