The authority of memory leak patterns in JavaScript

sponsored links
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
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of The authority of memory leak patterns in JavaScript

  • Understanding of JavaScript closures

    Understanding of JavaScript closures To become advanced JavaScript programmers, it is necessary to understand the closure. In this paper, ECMA 262 specification explain the closure of the internal working mechanism for JavaScript programmers understanding

  • AJAX projects at IE browser encountered "Internet Explorer can not open the site operation has been terminated" error solution

    Key words: IE, JavaScript, AJAX, Error: "Internet Explorer can not open the site, has ceased to operate" Wrong reasons: the page have not yet ready when the call htmlObject the appendChild or innerHTML operation. Solution: At appendChild or ...

  • js bind some of the ways in case notes

    Read some information online and found that some have compared several of the cow: the john resig Flexible Javascript Events (The code, itself, is very short and simple - only 15 lines long: ) dean.edwards expressed their views: My solution is very d ...

  • rails version of the change (1) - rails of the introduction

    Rails framework are at the first time in July 2004, its R & D is the 26-year-old Danes David Heinemeier Hansson. Different from complex Web development framework, Rails is more in line with actual needs and more efficient Web development framework. Ra

  • Optimize Debian / Ubuntu under ruby

    We all know that Debian / Ubuntu through apt-get to install the ruby packages very slow (Reference: Ruby implementation of various amendments to the Performance Evaluation version) Usually we are, through their own www.ruby-lang.org from the download sour

  • Rails to monitor the process of memory leaks skills

    Rails applications easier to encounter two types of performance problems: Rails implementation of a class are very slow, CPU consumption too high; The other is the process of memory leaks Rails. To resolve these two types of questions are necessary before

  • Depth understanding of Javascript closure (closure)

    Recently, online access to a lot of Javascript closure (closure) of relevant information and writing are very academic and professional. For beginners to understand let alone closure, and even the language describing it is very difficult to understan ...

  • ruby MBARI large patches Performance Evaluation Report

    Before JavaEye news ruby memory leak culprit - the specter of a detailed analysis of the current pointer Ruby official version (MRI version) causes memory leaks. Brent Roman today issued a Super patch , Which contains 6 patch file to resolve the Ruby ...

  • servlet specification 2.2

    Introduction: Spring Security watch, when to see more use of the Servlet Listener, filter and so on. Filter done, listener never. Therefore want from the Internet to find a closer look at the servlet specification, go thorough investigation, there is no s

  • Some interview questions java

    The first is the company give you a chance to meet, it is necessary to know to meet from time to equal the interview, and have a lot of companies to see you at the first time will give you a ready point of doing something trivial, these questions, althoug

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries