Table of Contents
##3.2 Timer Scenario example: " > Scenario example:
3.3 多处引用" >3.3 多处引用
3.4 闭包" >3.4 闭包
Home Web Front-end JS Tutorial Common memory leaks in JavaScript

Common memory leaks in JavaScript

Nov 09, 2020 pm 05:31 PM
javascript memory leak

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Go memory leak tracking: Go pprof practical guide Go memory leak tracking: Go pprof practical guide Apr 08, 2024 am 10:57 AM

The pprof tool can be used to analyze the memory usage of Go applications and detect memory leaks. It provides memory profile generation, memory leak identification and real-time analysis capabilities. Generate a memory snapshot by using pprof.Parse and identify the data structures with the most memory allocations using the pprof-allocspace command. At the same time, pprof supports real-time analysis and provides endpoints to remotely access memory usage information.

Solve the memory leak problem caused by closures Solve the memory leak problem caused by closures Feb 18, 2024 pm 03:20 PM

Title: Memory leaks caused by closures and solutions Introduction: Closures are a very common concept in JavaScript, which allow internal functions to access variables of external functions. However, closures can cause memory leaks if used incorrectly. This article will explore the memory leak problem caused by closures and provide solutions and specific code examples. 1. Memory leaks caused by closures The characteristic of closures is that internal functions can access variables of external functions, which means that variables referenced in closures will not be garbage collected. If used improperly,

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to avoid memory leaks in Golang technical performance optimization? How to avoid memory leaks in Golang technical performance optimization? Jun 04, 2024 pm 12:27 PM

Memory leaks can cause Go program memory to continuously increase by: closing resources that are no longer in use, such as files, network connections, and database connections. Use weak references to prevent memory leaks and target objects for garbage collection when they are no longer strongly referenced. Using go coroutine, the coroutine stack memory will be automatically released when exiting to avoid memory leaks.

How to detect memory leaks using Valgrind? How to detect memory leaks using Valgrind? Jun 05, 2024 am 11:53 AM

Valgrind detects memory leaks and errors by simulating memory allocation and deallocation. To use it, follow these steps: Install Valgrind: Download and install the version for your operating system from the official website. Compile the program: Compile the program using Valgrind flags (such as gcc-g-omyprogrammyprogram.c-lstdc++). Analyze the program: Use the valgrind--leak-check=fullmyprogram command to analyze the compiled program. Check the output: Valgrind will generate a report after the program execution, showing memory leaks and error messages.

Debugging techniques for memory leaks in C++ Debugging techniques for memory leaks in C++ Jun 05, 2024 pm 10:19 PM

A memory leak in C++ means that the program allocates memory but forgets to release it, causing the memory to not be reused. Debugging techniques include using debuggers (such as Valgrind, GDB), inserting assertions, and using memory leak detector libraries (such as Boost.LeakDetector, MemorySanitizer). It demonstrates the use of Valgrind to detect memory leaks through practical cases, and proposes best practices to avoid memory leaks, including: always releasing allocated memory, using smart pointers, using memory management libraries, and performing regular memory checks.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

How to effectively avoid memory leaks in closures? How to effectively avoid memory leaks in closures? Jan 13, 2024 pm 12:46 PM

How to prevent memory leaks in closures? Closure is one of the most powerful features in JavaScript, which enables nesting of functions and encapsulation of data. However, closures are also prone to memory leaks, especially when dealing with asynchronous and timers. This article explains how to prevent memory leaks in closures and provides specific code examples. Memory leaks usually occur when an object is no longer needed but the memory it occupies cannot be released for some reason. In a closure, when a function refers to external variables, and these variables

See all articles