4 kinds of common memory leaks in JS

Source: Internet
Author: User

First, what is a memory leak

Essentially, a memory leak is when a piece of memory is no longer being used by the application, and for some reason this memory is not returned to the operating system or to the free memory pool.

Ii. several common memory leaks

1. Unexpected global variables

A reference to a non-declared variable creates a new variable in the global object. In the context of the browser, the Global object is window, that is:

function Foo (ARG) {    = "This is a hidden global variable";}

is actually:

function Foo (ARG) {    = "This was an explicit global variable";}

In the above code, if bar is a reference to a variable within the scope of the Foo function, but forgets to declare the variable with VAR, it is equivalent to creating a global variable.

Another way to create a global variable by chance is as follows:

function foo () {    this. Variable = "Potential accidental global";} foo (); 

In the above code, the Foo function is called in the global scope, so this points to the window

Considerations for Global variables:

If you need a global variable to store a lot of data, you must make sure that it is set to null or re-assigned after use.

Common and global variables related to the increase in memory consumption caused by the cache. The cache stores reusable data.

To make this more efficient, you must specify an upper bound for the capacity of the cache. Because the cache cannot be reclaimed in a timely fashion, the unlimited growth of the cache can lead to high memory consumption.

2. Memory leaks due to closures

A closure can make a variable reside in memory, but if used improperly it becomes a memory leak

varTheThing =NULL;varReplacething =function () {  varOriginalthing =thething; varunused =function () {    if(originalthing) Console.log ("Hi");  }; TheThing={longstr:NewArray (1000000). Join (' * '), SomeMethod:function() {console.log (somemessage); }  };}; SetInterval (replacething,1000);

In the above code, each call replaceThing theThing will be given a new object that contains a large array and a new closure ( someMethod ).

At the same time, the unused variable holds a reference to originalThing the replaceThing closure (before the call theThing ).

The key problem is that the scope is shared whenever the scope of the closure is created under the same parent scope. In this case, the scope of someMethod the closures and unused the scopes are shared.

unusedHold a originalThing reference to it. Although unused it has never been used, it someMethod can be theThing accessed outside.

someMethodand, with the unused closure scope shared, even if it has unused never been used, the reference to it originalThing will force it to remain active (prevent it from being recycled).

When this code runs repeatedly, it will be observed that memory consumption is steadily rising and will not be degraded by the presence of the GC.

Essentially, a closed list (the root node is a theThing variant of the form) is created, and each closure scope holds an indirect reference to a large array, which results in a huge memory leak.

3. References outside the DOM

var elements={      button:document.getElementById ("button"),      Image: document.getElementById ("image"),      text:document.getElementById ("text")  };   function Dostuff () {      image.src= "Http://some.url/image";      Button.Click ():      console.log (text.innerhtml)  }  function  RemoveButton () {      Document.body.removeChild (document.getElementById (' button ')  }  )

2. Missing timer and callback function

var someresouce=getData ();  SetInterval (function() {      var node=document.getelementbyid (' node ');       if (node) {          node.innerhtml=json.stringify (someresouce)      }  },

In the above code, if the element with ID Node is removed from the DOM, the timer will still exist, and since the callback function contains a reference to Someresource, the someresource outside of the timer will not be released.

Third, how to avoid memory leaks

1) Reduce unnecessary global variables, or long life cycle of objects, timely garbage collection of useless data;

2) Pay attention to the program logic, avoid "dead loop" and the like;

3) Avoid creating too many object principles: no need to return the things in time.

4 kinds of common memory leaks in JS

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.