Home > Web Front-end > JS Tutorial > body text

Common memory leaks in JavaScript

coldplay.xixi
Release: 2020-11-09 17:31:37
forward
2683 people have browsed it

javascript column tutorial introduces common memory leaks.

Common memory leaks in JavaScript

  • Preface
  • 1 Introduction
  • 2 The main causes of memory leaks
  • 3 Common memory leaks
    • 3.1 Global variables
    • 3.2 Timer
    • 3.3 Multiple references
    • 3.4 Closure
  • 4 Chrome Memory Analysis Tool
  • Information

Preface

Reading this blog Before, you may need to have some knowledge of JavaScript memory management:

  • Memory management and garbage collection of JavaScript in V8

1 Introduction

Memory Leaks: refers to memory that is no longer needed by the application and is not returned to the operating system for some reason or Pool of Free Memory.

Potential problems caused by memory leaks: slowdown, lag, and high latency.

2 The main cause of memory leaks

The main cause of JavaScript memory leaks is some references that are no longer needed ( Unwanted References).

The so-called Unwanted References refers to: there are some memories that developers no longer need, but for some reason, these memories are still marked and remain in the active root tree. Unwanted References refers to references to these memories. In the context of JavaScript, Unwanted References are variables that are no longer used and point to some memory that could have been freed.

3 Common memory leaks

##3.1 Global variables

First of all, we need to know that global variables in JavaScript are referenced by the root node (root node), so they will not be garbage collected throughout the entire life cycle of the application.

Scenario 1: In JavaScript, if you reference an undeclared variable, it will cause a new variable to be created in the global environment.

function foo(arg) {    
bar = "this is a hidden global variable";
}
Copy after login

The above string of code is actually as follows:

function foo(arg) {   
window.bar = "this is an explicit global variable";
}
Copy after login

If we want the bar variable to be used only within the scope of the foo function, but the above situation will accidentally be used globally Creating bar within the scope will cause a memory leak.

Scenario 2:

function foo() {    
this.variable = "potential accidental global";
}foo();
Copy after login

Similarly, if we want the variable bar to be used only within the scope of the foo function, but if we do not know that this inside the foo function points to the global object, it will cause memory Give way.

Recommendation:

  1. Avoid accidentally creating global variables. For example, we can use strict mode, then the first piece of code in this section will report an error and no global variables will be created.

  2. #Reduce the creation of global variables.

  3. If you must use global variables to store large amounts of data, be sure to null or reallocate them after processing the data.

Scenario example:

for (var i = 0; i < 100000; i++) 
{    
var buggyObject = {        
callAgain: function () {            
var ref = this;            
var val = setTimeout(function () 
{                
ref.callAgain();            
}, 10);        
}    
}    
buggyObject.callAgain();    
buggyObject = null;}
Copy after login

3.3 多处引用

多处引用(Multiple references):当多个对象均引用同一对象时,但凡其中一个引用没有清除,都将导致被引用对象无法GC。

场景一:

var elements = 
{    
button: document.getElementById(&#39;button&#39;),    
image: document.getElementById(&#39;image&#39;),    
text: document.getElementById(&#39;text&#39;)};function doStuff() 
{    
image.src = &#39;http://some.url/image&#39;;    
button.click();    
console.log(text.innerHTML);    
// Much more logic}function removeButton() 
{    // The button is a direct child of body.    
document.body.removeChild(document.getElementById(&#39;button&#39;));    
// At this point, we still have a reference to #button in the global    
// elements dictionary. In other words, the button element is still in    
// memory and cannot be collected by the GC.s}
Copy after login

在上面这种情况中,我们对#button的保持两个引用:一个在DOM树中,另一个在elements对象中。 如果将来决定回收#button,则需要使两个引用均不可访问。在上面的代码中,由于我们只清除了来自DOM树的引用,所以#button仍然存在内存中,而不会被GC。

场景二: 如果我们想要回收某个table,但我们保持着对这个table中某个单元格(cell)的引用,这个时候将导致整个table都保存在内存中,无法GC。

3.4 闭包

闭包(Closure):闭包是一个函数,它可以访问那些定义在它的包围作用域(Enclosing Scope)里的变量,即使这个包围作用域已经结束。因此,闭包具有记忆周围环境(Context)的功能。

场景举例:

var newElem;function outer() 
{   
var someText = new Array(1000000);   
var elem = newElem;   
function inner() 
{       if (elem) return someText;  
 }   
 return function () {};
 }setInterval(function ()
  {   newElem = outer();}, 5);
Copy after login

在这个例子中,有两个闭包:一个是inner,另一个是匿名函数function () {}。其中,inner闭包引用了someText和elem,并且,inner永远也不会被调用。可是,我们需要注意:相同父作用域的闭包,他们能够共享context。 也就是说,在这个例子中,inner的someText和elem将和匿名函数function () {}共享。然而,这个匿名函数之后会被return返回,并且赋值给newElem。只要newElem还引用着这个匿名函数,那么,someText和elem就不会被GC。

同时,我们还要注意到,outer函数内部执行了var elem = newElem;,而这个newElem引用了上一次调用的outer返回的匿名函数。试想,第n次调用outer将保持着第n-1次调用的outer中的匿名函数,而这个匿名函数由保持着对elem的引用,进而保持着对n-2次的...因此,这将造成内存泄漏。

Solution: Change the code of parameter 1 in setInterval to newElem = outer()();

For detailed analysis of this section, please see Material 1 and information 2.

4 Chrome Memory Analysis Tool

Chrome (latest version 86) developer tools Two analysis tools about memory:

  1. Performance

  2. ##Memory

##Related free learning recommendations:
javascript

(video)

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

Related labels:
source:juejin.im
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template