Common JavaScript memory leaks

Source: Internet
Author: User

Memory leak: The program failed to release memory that is no longer in use due to negligence or error. A memory leak does not mean that there is physical disappearance, but that after the application allocates a piece of memory, because of a design error, it loses control of the memory before releasing the memory, resulting in a waste of memory. 1. Unexpected global variables

JS pairs an undeclared variable creates its reference on the highest global object, which is a property, not a variable, if it is a Window object on the browser, if it is global in the node environment, and if the undeclared variable caches large amounts of data, It may only release memory when the page is refreshed or closed, causing an accidental memory leak. Here's an example:

function My () {    name="my name is Tokey"}my () console.log (window)

In the console you can see

and create an unexpected global variable through this.

function My () {    this.name='my name is Tokey'}my () Console.log ( Window.name)//my name is Tokey The this point is not undefined but the Global object window

For memory leaks of the above type we must declare the variable in peacetime, do not have a global direct reference. (added in JavaScript file ‘use strict‘ , open Strict mode, can effectively avoid the above problems.) )

2, Console.log

It is very common to use console.log as the front end to make the corresponding information in the console. However, if you do not remove Console.log, there may be a memory leak. Because the object information needs to be viewed in the development tool after the code is run, the object passed to Console.log cannot be garbage collected.

3. Closed Package

First the closure is a function a returns an inline function B, in a timely manner a function finished function B can also access the variables inside function A, this is a simple closure. Essentially closures are a bridge that connects the functions inside and outside.

function my (name) {    function sendname () {        console.log (name)    }    return  sendname }var test=my ("tokey") test ()  //Tokey 

The Sendname () function created inside my () is not recycled because it is referenced by the global variable test and is in a state that is called at any time. If the memory can be set to release Test=null; Because the closure carries the scope of the function that contains it, it consumes more memory than the other functions. Excessive use of closures may result in excessive memory consumption.

4. Dom leaks

The DOM and JS in the browser use a different engine, Dom uses the rendering engine, and JS uses the V8 engine, so it is more expensive to manipulate the DOM with JS because they need a bridge to link them. In order to reduce the DOM operation, we will generally use the DOM. We will take a variable reference in a way that caches it in the current environment. If, after some deletions, updates, you may forget to release the DOM that has been cached, say no more directly to an example

<! DOCTYPE html>"en">"UTF-8"> <meta name="Viewport"Content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,initial-scale=1.0, Width=device-width"> <title>Title</title> <style> *{margin:0; padding:0; }    </style>class="Main"> <divclass="Test"> Days </div> <divclass="Item"> Days </div> <divclass="Item"> To </div></div><button id="Add"> Click I add </button><button id="Remove"> Click I reduce </button></body><script src="Js/zepto.js"></script><script src="Http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script><script>varAdd=document.queryselector ("#add");varRemove=document.queryselector ("#remove");varMain=document.queryselector (". Main")varTest=document.queryselector (". Test") Add.onclick=function () {varItemn=document.createelement ('Div')    varTxt=document.createtextnode ('on') itemn.appendchild (TXT) main.appendchild (itemn)}remove.onclick=function () {Main.removechild (test)}</script>

With the Chrome Viewer's memory debugging work, we can see

After I clicked on three increments, it was obvious that the node (Green Line) had three noticeable increases, then I deleted a node, but the Green Line didn't drop, which is why?, this is the memory leak. The reason is that the deleted DOM has a global reference in JS. That is, I deleted the test is referenced in the text, so I cannot free memory. So you should set it to null after you delete an update, and so on.

5. Forgotten Timers

JS commonly used Timers setinterval (), SetTimeout (). They are all required to delay a certain amount of time to execute a code where SETINTERVAL () and chained setTimeout () are not manually closed after use. There will always be execution memory, so we can use Clearinterval (), cleartimeout () to turn off the corresponding timer and free up memory when not in use. Familiar with friends know that this kind of timer is error, so the tour device gives a special api-requestanimationframe (); You can try it.

Common JavaScript memory leaks

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.