The authority of memory leak patterns in JavaScript

If you know the cause of memory leak, then the corresponding JavaScript should be fairly easy to prevent. In this article, the author Kiran Sundar and Abhijeet Bhattacharya will take you to experience the JavaScript references in the full cycle of basic knowledge, to introduce you to why they would cause problems in some browsers, especially when combined with the closure of the case next. To understand that you should draw attention to the common memory leak mode, you will also learn the many ways to address these leaks.

JavaScript is used to add dynamic content to the Web page is a powerful scripting language. In particular, it especially useful for routine tasks such as authentication password, and create a dynamic menu component. JavaScript easy to learn, but very easy to cause some browsers to leak memory. In this introductory article, we explain how JavaScript in the leak caused by the display of the common memory leak patterns, and describes how to deal with them.

Note This article assumes that you already familiar with JavaScript and the DOM element to develop Web applications. This particular suitable for use JavaScript for Web application development developers, also available for applications interested in creating Web browsers support customers in the browser and the responsible officers on troubleshooting.

JavaScript memory leaks in

JavaScript is a garbage collection-type language, which means that memory is based on the creation of the object assigned to the object, and will in the absence of reference to the object recovered by browsing device. JavaScript's garbage collection mechanism itself, and there is no problem, but the browser DOM object for memory allocation and recovery is some way out.

Internet Explorer and Mozilla Firefox are using reference counting to handle the memory for the DOM object. In the reference counting system, each object referenced will keep a count, as to be aware how many objects are referencing it. If the count is zero, the object will be destroyed, their occupation will be returned to the heap memory. Although this solution in general is still considered effective, but there are some circular reference side has blind spots.

Circular reference issue?

When two objects reference each other when, on the form of a circular reference, in which the reference count for each object are assigned 1. Pure garbage collection system, the circular reference problem is not: if the two objects involved in an object by any other object reference, then the two objects will be garbage collected. In the reference counting system, the two objects are not be destroyed, because the reference count can never be zero. At the same time using the garbage collection and reference counting hybrid system will be leaks, because the system can not correctly identify the circular reference. In this case, DOM and JavaScript objects are not objects can be destroyed. Listing 1 shows the JavaScript objects and DOM objects exist in a circular reference.

Listing 1. Circular reference cause a memory leak
<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> Div Element </ div>
</ Body>
</ Html>

As shown in the above list, JavaScript object obj to the DOM object has a reference, expressed as DivElement. The DOM object is a reference to this JavaScript object by expandoProperty said. Visible, JavaScript objects and DOM objects to produce a circular reference. As the DOM object is managed by reference count, so the two objects can not be destroyed.

Another memory leak mode

2 in the list, by calling the external function myFunction create circular references. Similarly, JavaScript objects and DOM objects in the circular reference will cause a memory leak.

Listing 2. By an external function call due to memory leak
<html>
<head>
<script type="text/javascript">
document.write ("object s 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> </ div>
</ Body>
</ Html>

As shown in the two code samples, is easy to create a circular reference. In the JavaScript programming structure one of the most convenient: the closure, the cycle of reference particularly conspicuous.

JavaScript in the closure

JavaScript excels is that it allows the function nested. Inside a nested function can inherit the parameters of the external functions and variables by the external function private. Listing 3 shows an example of an internal function.

Listing 3. An internal function
function parentFunction (paramA)
(
var a = paramA;
function childFunction ()
(
return a + 2;
)
return childFunction ();
)

Developers use JavaScript function to other functions within the integrated small-scale practical function. Shown in Listing 3, the internal functions can access external functions parentFunction childFunction variables. When the internal function to obtain and use its external function of variables, it called for a closure.

Learn closure

Consider the code shown in Listing 4 fragment.

Listing 4. A simple closure
<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 list, closureDemoInnerFunction is defined in the parent function closureDemoParentFunction internal functions. When using an external x-on closureDemoParentFunction calls, the external function will be assigned a variable outside of x. Function returns a pointer pointing to an internal function closureDemoInnerFunction, the pointer included in the variable x inside.

External function closureDemoParentFunction a local variable even in the outer function returns will continue. This is different from the C / C + + like programming language, in C / C + +, once the function returns, the local variable will no longer exist. In JavaScript, calling closureDemoParentFunction when a range of objects with properties will be created. The properties include the value of paramA, also known as "external x". Similarly, when closureDemoParentFunction returns, it will return the internal function closureDemoInnerFunction, the function included in the variable x in.

As the internal function held until the outer function's variables of reference, so the scope of a object with a property will not be garbage collection. When a parameter value on the inner x of x to call, that is, x ("inner x"), will pop up a warning message that "outer x innerx".

Listing 4 briefly explains the JavaScript closures. Closure is very powerful because they make the internal function in the external function returns, still able to retain this access outer function's variables. Unfortunately, closure is very easy to hide the JavaScript objects and DOM objects in the circular reference.

Closures and circular references

In Listing 5, you can see a closure, closure in this period, JavaScript Object (obj) include a reference to the DOM object (by id "element" is referenced). The DOM element holds a reference to the JavaScript obj. This built JavaScript objects and DOM objects in the circular reference will cause a memory leak.

Listing 5. Caused by the event processing model of memory leaks
<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> Click Me </ button>
</ Body>
</ Html>

To avoid memory leaks

Fortunately, JavaScript memory leaks in can be avoided. When the identified model can lead to circular references after the chapter in as we did above, you can respond to these patterns has started. Here, we will deal with the incident caused by a memory leak model as an example to show three kinds of way to deal with known memory leaks.

One kind of response to a memory leak in the list of five solutions to this JavaScript object obj is null, which explicitly break the circular reference, as shown in Listing 6.

Listing 6. To break the cycle of reference
<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> "Click Here" </ button>
</ Body>
</ Html>

Listing 7 is the addition of another closure to avoid JavaScript objects and DOM objects in the circular reference.

Listing 7. Add another closure
<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> "Click Here" </ button>
</ Body>
</ Html>

Listing 8 by adding another function to avoid the closure itself, and thus prevent a leak.

Listing 8. To avoid the closure of its own
<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> "Click Here" </ button>
</ Body>
</ Html>

Transfer from: http://04js.cn/content.asp?id=1610

分类:Web 时间:2010-06-01 人气:249
分享到:
blog comments powered by Disqus

相关文章

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.599 (s). 12 q(s)