Home  >  Article  >  Web Front-end  >  What are the causes of JavaScript memory leaks?

What are the causes of JavaScript memory leaks?

青灯夜游
青灯夜游Original
2021-11-19 16:37:514370browse

Causes of JavaScript memory leaks: 1. Improper use of global variables; 2. Improper use of closures; 3. Delays or timers are not cleared; 4. DOM element references that are not cleared (dom cleared or The event is not cleared when deleted).

What are the causes of JavaScript memory leaks?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Memory leak means that a piece of allocated memory cannot be used or recycled until the browser process ends. This means that due to negligence or error, the program fails to release memory that is no longer used. Memory leaks do not refer to the physical disappearance of memory, but rather to the fact that after the application allocates a certain segment of memory, due to a design error, the control of the segment of memory is lost before the segment of memory is released, thus causing memory corruption. waste. Here are some common causes of memory leaks.

1. Global variables

JavaScript can handle undeclared variables: a reference to an undeclared variable creates a new variable in the global object. In the context of a browser, the global object is window.

function foo(){
  name = '前端曰';
}
// 其实是把name变量挂载在window对象上
function foo(){
  window.name = '前端曰';
}

// 又或者
function foo(){
  this.name = '前端曰';
}
foo() // 其实这里的this就是指向的window对象

In this way, an unexpected global variable is created unintentionally. To prevent this error from happening, add ‘use strict;’ at the front of your Javascript file. This enables a stricter mode of parsing JavaScript that prevents unexpected globals. Or pay attention to the definition of variables yourself!

2. Closure

Closure: Anonymous functions can access variables in the parent scope.

var names = (function(){  
    var name = 'js-say';
    return function(){
        console.log(name);
    }
})()

Closing will cause the life cycle of the object reference to be separated from the context of the current function. If the closure is used improperly, it can lead to a circular reference (circular reference), similar to a deadlock, which can only be avoided and cannot be solved after it occurs. , even with garbage collection, memory leaks will still occur.

3. The forgotten delayer/timer

In our daily needs, we may often try setInterval/setTimeout, but we usually forget to clean it up after use.

var someResource = getData(); 
setInterval(function() { 
    var node = document.getElementById('Node'); 
    if(node) { 
        // 处理 node 和 someResource 
        node.innerHTML = JSON.stringify(someResource)); 
    } 
}, 1000);

This in setInterval/setTimeout points to the window object, so the internally defined variables are also mounted globally; the someResource variable is referenced in the if, and if setInterval/setTimeout is not cleared, someResource will not be released. ;Similarly, the same is true for setTimeout. So we need to remember to clearInterval/clearTimeout when finished.

4. DOM element references that are not cleared (When the dom is cleared or deleted, the event is not cleared)

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'));
    // 此时,仍旧存在一个全局的 #button 的引用
    // elements 字典。button 元素仍旧在内存中,不能被 GC 回收。
}

[Recommended learning: javascript Advanced Tutorial

The above is the detailed content of What are the causes of JavaScript memory leaks?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What is li in htmlNext article:What is li in html