Memory leakage mode in authoritative JavaScript

Source: Internet
Author: User

Author:
Abhijeet Bhattacharya, system software engineer, IBM India
Kiran Shivarama Sundar (kisundar@in.ibm.com), system software engineer, IBM India

May 28, 2007

If you know the cause of Memory leakage, it is quite easy to prevent it in JavaScript. In this article, the authors Kiran Sundar and Abhijeet Bhattacharya will show you all the basic knowledge of loop references in JavaScript and explain to you why they have problems in some browsers, especially when closure is integrated. After learning about the common memory leakage modes that you should pay attention to, you will also learn many methods to deal with these leaks.

JavaScript is a powerful scripting language used to add dynamic content to Web pages. It is particularly helpful for some daily tasks, such as verifying passwords and creating dynamic menu components. JavaScript is easy to learn and use, but it is easy to cause memory leakage in Some browsers. In this introductory article, we explain how JavaScript leaks are caused, demonstrate common memory leak patterns, and explain how to deal with them.

Note: This article assumes that you are very familiar with using JavaScript and DOM elements to develop Web applications. This article is especially suitable for developers who use JavaScript For Web application development. It can also be used by users who are interested in creating Web applications to provide browser support and help those who are responsible for browser troubleshooting.

Memory leakage in JavaScript

JavaScript is a garbage collection language, which means that the memory is allocated to the object based on the object creation and will be reclaimed by the browser when no reference is made to the object. The garbage collection mechanism of JavaScript is no problem, but the browser is somewhat different in the way of allocating DOM objects and Restoring memory.

Both Internet Explorer and Mozilla Firefox use reference count to process memory for DOM objects. In the reference counting system, each referenced object retains a count to learn how many objects are referencing it. If the count is zero, the object will be destroyed and the occupied memory will be returned to the heap. Although this solution is still effective in general, there are some blind spots in circular references.

What are the problems with circular references?

When two objects reference each other, a circular reference is formed. The reference count value of each object is assigned 1. In a pure garbage collection system, loop reference is not a problem: if one of the two objects involved is referenced by any other object, both objects will be collected by garbage collection. In the reference counting system, neither of these two objects can be destroyed because the reference counting cannot be zero. In a hybrid system that uses both garbage collection and reference count, leakage occurs because the system cannot correctly identify cyclic references. In this case, neither the DOM object nor the JavaScript Object can be destroyed. Listing 1 shows a circular reference between a JavaScript Object and a DOM object.

Listing 1. Loop reference causes memory leakage

As shown in the above list, the JavaScript ObjectobjReference to a DOM object, representedDivElement. The DOM object has reference to this JavaScript ObjectexpandoProperty. It can be seen that a circular reference is generated between a JavaScript Object and a DOM object. Because DOM objects are managed by reference count, neither of them can be destroyed.

Another memory leakage Mode

In Listing 2, by calling an external FunctionmyFunctionCreate a circular reference. Similarly, circular references between JavaScript objects and DOM objects may cause memory leakage.

List 2. Memory leakage caused by external function calls

new myFunction(document.getElementById("myDiv"));}</script>

As shown in the two sample codes, circular references are easy to create. Loop references are particularly prominent in one of the most convenient programming structures of JavaScript: closures.

Closure in JavaScript

JavaScript allows nested functions. A nested internal function can inherit the parameters and variables of an external function and is private to the external function. 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();}

JavaScript developers use internal functions to integrate small practical functions into other functions. As shown in listing 3, this internal functionchildFunctionAccess external functionsparentFunction. When an internal function obtains and uses the variables of its external function, it is calledClosure.

Understanding closures

Consider the code snippets shown in Listing 4.

Listing 4. A simple closure

In the above list,closureDemoInnerFunctionIs in the parent FunctionclosureDemoParentFunctionInternal functions defined in. When usingExternal xPairclosureDemoParentFunctionExternal function variablesAThe value is assignedExternal x. The function returns a pointer to an internal function.closureDemoInnerFunctionPointer, which is included in the VariableX.

External FunctionsclosureDemoParentFunctionLocal variableAEven when the external function returns, it still exists. This is different from a programming language like C/C ++. in C/C ++, once the function returns, the local variable will no longer exist. In JavaScriptclosureDemoParentFunctionWith PropertiesAWill be created. This property includes valuesParamA, Also known"External x". Similarly, whenclosureDemoParentFunctionIt returns an internal function.closureDemoInnerFunction, This function is included in the VariableX.

Because the internal function holds a reference to the variable of the external function, this includes an attribute.AWill not be collected by garbage collection. When a pair has a parameter valueInner xOfXWhen calling, that isx("inner x"), A warning message is displayed, indicating"Outer x innerx".

Listing 4 briefly explains the JavaScript closure. Closures are very powerful because they allow internal functions to retain access to the variables of this external function when the external function returns. Unfortunately, closures are very easy to hide circular references between JavaScript objects and DOM objects.

Closures and circular references

In listing 5, you can see a closure in which the JavaScript Object (obj) Include references to the DOM object (by id"element"Referenced ). While DOM elements have JavaScriptobj. In this way, the circular reference between the created JavaScript Object and the DOM object will cause memory leakage.

Listing 5. Memory leakage mode caused by event processing

Avoid Memory leakage

Fortunately, memory leakage in JavaScript can be avoided. After you have determined the patterns that can cause cyclic reference, as we have done in the previous sections, you can start to deal with these patterns. Here, we will take the memory leakage mode caused by event processing as an example to demonstrate three methods to deal with known memory leaks.

A solution to address memory leakage in listing 5 is to make this JavaScript ObjectobjThis explicitly breaks this circular reference, as shown in Listing 6.

Listing 6. Breaking circular references

obj = null; //This breaks the circular reference};</script><button id="element">"Click Here"</button></body>

Listing 7 is to avoid circular references between JavaScript objects and DOM objects by adding another closure.

Listing 7. Add another Closure

In listing 8, another function is added to avoid the closure and prevent leakage.

Listing 8. Avoid closure itself

function doesNotLeak(){//Your Logic herealert("Hi! I have avoided the leak");}</script>

Conclusion

This article explains how loop references cause memory leakage in JavaScript-especially when closures are combined. You also learned some common memory leak modes that involve cyclic references and several simple methods to cope with these leak modes.

Author Profile

Abhijeet Bhattacharya is a system engineer at the IBM India software lab. He has been a member of the OS/2 IBM Web Browser Support Team for the past three years. He also has experience in the system management field and has participated in the IBM Pegasus open-source innovation project. His current work focuses on distributed computing and SARPC. He has a bachelor's degree in engineering from Rajiv Gandhi Technical University.

Kiran Shivarama Sundar is a system engineer at the IBM India software lab. He has been a member of the OS/2 IBM Web Browser Support Team for the past three years. He also has experience in many other projects, including developing command line tools for the Apache Tuscany Open Source Project and RFIDIC Installer for the ibm epcis team. Currently, Kiran has joined the IBM WebSphere Adapters support team to provide support for JMS and MQ Adapters. He has been successfully Certified by Sun Certified Java Programmer, Sun Certified Web Component Developer, and Sun Certified Business Component Developer. He currently focuses on Java, J2EE, Web Services, and SOA. He has a bachelor's degree in engineering from Visweshwaraya Technology University.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.