Memory leak patterns in JavaScript

Handling circular references in JavaScript applications

Abhijeet Bhattacharya and Kiran Shivarama Sundar
Published on April 24, 2007

JavaScript is a powerful scripting language used to add dynamic content to Web pages. It is especially beneficial for everyday tasks such as password validation and creating dynamic menu components. While JavaScript is easy to learn and write, it is prone to memory leaks in certain browsers. In this introductory article we explain what causes memory leaks in JavaScript, demonstrate some of the common memory leak patterns to watch out for, and show you how to work around them.

Note that the article assumes you are familiar with using JavaScript and DOM elements to develop Web applications. The article will be most useful to developers who use JavaScript for Web application development. It might also serve as a reference for those providing browser support to clients rolling out Web applications or for anyone tasked with troubleshooting browser issues.

Is my browser leaking?

Internet Explorer and Mozilla Firefox are the two Web browsers most commonly associated with memory leaks in JavaScript. The culprit in both browsers is the component object model used to manage DOM objects. Both the native Windows COM and Mozilla's XPCOM use reference-counting garbage collection for memory allocation and retrieval. Reference counting is not always compatible with the mark-and-sweep garbage collection used for JavaScript. This article focuses on ways to work around memory leaks in JavaScript code. SeeRelated topics to learn more about COM layer memory handling in Firefox and IE.

Memory leaks in JavaScript

JavaScript is a garbage collected language, meaning that memory is allocated to objects upon their creation and reclaimed by the browser when there are no more references to them. While there is nothing wrong with JavaScript's garbage collection mechanism, it is at odds with the way some browsers handle the allocation and recovery of memory for DOM objects.

Internet Explorer and Mozilla Firefox are two browsers that use reference counting to handle memory for DOM objects. In a reference counting system, each object referenced maintains a count of how many objects are referencing it. If the count becomes zero, the object is destroyed and the memory is returned to the heap. Although this solution is generally very efficient, it has a blind spot when it comes to circular (or cyclic) references.

What's wrong with circular references?

A circular reference is formed when two objects reference each other, giving each object a reference count of 1. In a purely garbage collected system, a circular reference is not a problem: If neither of the objects involved is referenced by any other object, then both are garbage collected. In a reference counting system, however, neither of the objects can be destroyed, because the reference count never reaches zero. In a hybrid system, where both garbage collection and reference counting are being used, leaks occur because the system fails to identify a circular reference. In this case, neither the DOM object nor the JavaScript object is destroyed. Listing 1 shows a circular reference between a JavaScript object and a DOM object.

Listing 1. A circular reference resulting in a memory leak
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<html>
    <body>
    <script type="text/javascript">
    document.write("Circular references between JavaScript and DOM!");
    var obj;
    window.onload = function(){
    obj=document.getElementById("DivElement");
            document.getElementById("DivElement").expandoProperty=obj;
            obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX"));
            };
    </script>
    <div id="DivElement">Div Element</div>
    </body>
    </html>

As you can see in the above listing, the JavaScript object obj has a reference to the DOM object represented by DivElement. The DOM object, in turn, has a reference to the JavaScript object through theexpandoProperty. A circular reference exists between the JavaScript object and the DOM object. Because DOM objects are managed through reference counting, neither object will ever be destroyed.

Another memory leak pattern

In Listing 2 a circular reference is created by calling the external function myFunction. Once again the circular reference between a JavaScript object and a DOM object will eventually lead to a memory leak.

Listing 2. A memory leak caused by calling an external function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<html>
<head>
<script type="text/javascript">
document.write("Circular references between JavaScript and DOM!");
function myFunction(element)
{
    this.elementReference = element;
    // This code forms a circular reference here
    //by DOM-->JS-->DOM
    element.expandoProperty = this;
}
function Leak() {
    //This code will leak
    new myFunction(document.getElementById("myDiv"));
}
</script>
</head>
<body onload="Leak()">
<div id="myDiv"></div>
</body>
</html>

As these two code samples show, circular references are easy to create. They also tend to crop up quite a bit in one of JavaScript's most convenient programming constructs: closures.

Closures in JavaScript

One of JavaScript's strengths is that it allows functions to be nested within other functions. A nested, or inner, function can inherit the arguments and variables of its outer function, and is private to that function. Listing 3 is an example of an inner function.

Listing 3. An inner function
1
2
3
4
5
6
7
8
9
function parentFunction(paramA)
{
        var a = paramA;
        function childFunction()
        {
        return a + 2;
        }
        return childFunction();
}

JavaScript developers use inner functions to integrate small utility functions within other functions. As you can see in Listing 3, the inner function childFunction has access to the variables of the outerparentFunction. When an inner function gains and uses access to its outer function's variables it is known as a closure.

Learning about closures

Consider the code snippet shown in Listing 4.

Listing 4. A simple closure
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<html>
<body>
<script type="text/javascript">
document.write("Closure Demo!!");
window.onload=
function  closureDemoParentFunction(paramA)
{
    var a = paramA;
    return function closureDemoInnerFunction (paramB)
    {
            alert( a +" "+ paramB);
    };
};
var x = closureDemoParentFunction("outer x");
x("inner x");
</script>
</body>
</html>

In the above listing closureDemoInnerFunction is the inner function defined within the parent functionclosureDemoParentFunction. When a call is made to closureDemoParentFunction with a parameter of outer x, the outer function variable a is assigned the value outer x. The function returns with a pointer to the inner function closureDemoInnerFunction, which is contained in the variable x.

It is important to note that the local variable a of the outer function closureDemoParentFunction will exist even after the outer function has returned. This is different from programming languages such as C/C++, where local variables no longer exist once a function has returned. In JavaScript, the momentclosureDemoParentFunction is called, a scope object with property a is created. This property contains the value of paramA, also known as "outer x". Similarly, when the closureDemoParentFunction returns, it will return the inner function closureDemoInnerFunction, which is contained in the variable x.

Because the inner function holds a reference to the outer function's variables, the scope object with property a will not be garbage collected. When a call is made on x with a parameter value of inner x -- that is,x("inner x") -- an alert showing "outer x innerx" will pop up.

Listing 4 is a very simple illustration of a JavaScript closure. Closures are powerful because they enable inner functions to retain access to an outer function's variables even after the outer function has returned. Unfortunately, closures are excellent at hiding circular references between JavaScript objects and DOM objects.

Closures and circular references

In Listing 5 you see a closure in which a JavaScript object (obj) contains a reference to a DOM object (referenced by the id "element"). The DOM element, in turn, has a reference to the JavaScript obj. The resulting circular reference between the JavaScript object and the DOM object causes a memory leak.

Listing 5. Event handling memory leak pattern
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html>
<body>
<script type="text/javascript">
document.write("Program to illustrate memory leak via closure");
window.onload=function outerFunction(){
    var obj = document.getElementById("element");
    obj.onclick=function innerFunction(){
    alert("Hi! I will leak");
    };
    obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX"));
    // This is used to make the leak significant
};
</script>
<button id="element">Click Me</button>
</body>
</html>

Avoiding memory leaks

The upside of memory leaks in JavaScript is that you can avoid them. When you have identified the patterns that can lead to circular references, as we've done in the previous sections, you can begin to work around them. We'll use the above event-handling memory leak pattern to demonstrate three ways to work around a known memory leak.

One solution to the memory leak in Listing 5 is to make the JavaScript object obj null, thus explicitly breaking the circular reference, as shown in Listing 6.

Listing 6. Break the circular reference
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<html>
<body>
<script type="text/javascript">
document.write("Avoiding memory leak via closure by breaking the circular
reference");
    window.onload=function outerFunction(){
    var obj = document.getElementById("element");
    obj.onclick=function innerFunction()
    {
        alert("Hi! I have avoided the leak");
        // Some logic here
    };
    obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX"));
    obj = null; //This breaks the circular reference
    };
</script>
<button id="element">"Click Here"</button>
</body>
</html>

In Listing 7 you avoid the circular reference between the JavaScript object and the DOM object by adding another closure.

Listing 7. Add another closure
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<html>
<body>
<script type="text/javascript">
document.write("Avoiding a memory leak by adding another closure");
window.onload=function outerFunction(){
var anotherObj = function innerFunction()
         {
            // Some logic here
            alert("Hi! I have avoided the leak");
         };
     (function anotherInnerFunction(){
        var obj =  document.getElementById("element");
        obj.onclick=anotherObj })();
        };
</script>
<button id="element">"Click Here"</button>
</body>
</html>

In Listing 8 you avoid the closure itself by adding another function, thereby preventing the leak.

Listing 8. Avoid the closure altogether
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<html>
<head>
<script type="text/javascript">
document.write("Avoid leaks by avoiding closures!");
window.onload=function()
{
    var obj = document.getElementById("element");
    obj.onclick = doesNotLeak;
}
function doesNotLeak()
{
    //Your Logic here
    alert("Hi! I have avoided the leak");
}
 
</script>
</head>
<body>
<button id="element">"Click Here"</button>
</body>
</html>

In conclusion

This article has explained how circular references can lead to memory leaks in JavaScript, particularly when combined with closures. You've seen several common memory leak patterns involving circular references and some easy ways to work around them. See Related topics to learn more about the topics discussed in this introductory article.

http://www.ibm.com/developerworks/web/library/wa-memleak/?S_TACT=105AGX52&S_CMP=cn-a-wa

JavaScript :memory leak [转]的更多相关文章

  1. Linux C/C++ Memory Leak Detection Tool

    目录 . 内存使用情况分析 . 内存泄漏(memory leak) . Valgrind使用 1. 内存使用情况分析 0x1: 系统总内存的分析 可以从proc目录下的meminfo文件了解到当前系统 ...

  2. Memory leak patterns in JavaScript

    Handling circular references in JavaScript applications Plugging memory leaks in JavaScript is easy ...

  3. Android 内存管理 &Memory Leak & OOM 分析

    转载博客:http://blog.csdn.net/vshuang/article/details/39647167 1.Android 进程管理&内存 Android主要应用在嵌入式设备当中 ...

  4. quartz集群报错but has failed to stop it. This is very likely to create a memory leak.

    quartz集群报错but has failed to stop it. This is very likely to create a memory leak. 在一台配置1核2G内存的阿里云服务器 ...

  5. 山东省第七届ACM省赛------Memory Leak

    Memory Leak Time Limit: 2000MS Memory limit: 131072K 题目描述 Memory Leak is a well-known kind of bug in ...

  6. caching redirect views leads to memory leak (Spring 3.1)

    在Spring 3.1以及以下版本使用org.springframework.web.servlet.view.UrlBasedViewResolver + cache(如下配置),在会出现任意种re ...

  7. 一则JVM memory leak解决的过程

    起因是我们的集群应用(3台机器)新版本测试过程中,一般的JVM内存占用 都在1G左右, 但在运行了一段时间后,慢慢升到了4G, 这是一个明显不正常的现象. 定位 过程: 1.先在该机器上按照步骤尝试重 ...

  8. SilverLight - Memory Leak

    There is a memory leak issue in current silverlight project. It occurs in the search function: the m ...

  9. A memory leak issue with WPF Command Binding

    Background In our application, we have a screen which hosts several tabs. In each tab, it contains a ...

随机推荐

  1. AJAX入门——工作原理

    同步和异步交互,了解互动 对于一个样本:一般B/S模式(同步)       AJAX技术(异步)        *  同步:       提交请求->等待server处理->处理完成返回 ...

  2. Android 发展 ------------- Unable to resolve target &#39;android-19&#39;

    又一次装完Ecplise+ATD+Android SDK 在Ecplise工作空间导入之前写过的Android项目会出现错误,大部分是SDK 版本号不符,例如以下错误提示: Error:Unable ...

  3. js实现多张图片同时放大缩小相对位置不变

    项目要求需要用js实现同时放大多张图片相对位置不变,就和同事去一家国外网站的js文件中跟踪扒取了这一算法, 庆幸的是算法抠出来了并整理了出来,但遗憾的只知计算过程却弄不明白算法原理: 大体上是核心运算 ...

  4. 带你走近AngularJS 之创建自定义指令

    带你走近AngularJS 之创建自定义指令 为什么使用AngularJS 指令? 使用过 AngularJS 的朋友应该最感兴趣的是它的指令.现今市场上的前端框架也只有AngularJS 拥有自定义 ...

  5. Ubuntu下LaTex中文环境安装与配置

    转载自:http://www.linuxidc.com/Linux/2012-06/62456.htm LaTeX是一个强大的排版软件,但是其最初只是为英文排版而设计的.为了使其能够胜任中文排版的重任 ...

  6. HTML初学者的三十条最佳

    颜海镜 专注web前端,分享html,css,javascript等相关知识…… 给HTML初学者的三十条最佳实践 Nettuts +运营最困难的方面是为很多技能水平不同的用户提供服务.如果我们发布太 ...

  7. Visual Stuido也有非常多的快捷键

    最近看到很多同事用 VI 来开发Ruby,Python脚本. 编辑代码全部用的是快捷键,效率很高. 其实Visual Stuido也有非常多的快捷键,熟练运用后,能大大提高工作效率. 本文介绍一些最常 ...

  8. [转]Mac OS X local privilege escalation (IOBluetoothFamily)

    Source: http://joystick.artificialstudios.org/2014/10/mac-os-x-local-privilege-escalation.html Nowad ...

  9. 红黑树LLRB

    LLRB——红黑树的现代实现 一.本文内容 以一种简明易懂的方式介绍红黑树背后的逻辑实现2-3-4树,以及红黑树的插入.删除操作,重点在2-3-4树与红黑树的对应关系上,并理清红黑树相关操作的来龙去脉 ...

  10. JDBC之事务隔离级别以及ACID特性

    JDBC之事务隔离级别以及ACID特性 事务隔离级别: 1.更新遗失(Lost update) 两个事务都同时更新一行数据,但是第二个事务却中途失败退出,导致对数据的两个修改都失效了.这是因为系统没有 ...