Home Web Front-end JS Tutorial What is a memory leak and how to fix it

What is a memory leak and how to fix it

Mar 16, 2019 am 11:49 AM
memory leak

Memory leak means that when an object is ineffective and should be recycled, but it cannot be recycled because of another object's reference to it, and it remains in the heap memory, it is called a memory leak. Common ones include unexpected global variables, DOM leaks and circular references, etc.

What is a memory leak and how to fix it

[Recommended course: JavaScript Tutorial

Memory leak

Memory leak generally refers to when an object has no effect and should be recycled. Another object in use cannot be recycled due to its reference. This object that cannot be recycled stays in the heap memory, which causes a memory leak.

When an object is no longer needed When the object that is supposed to be recycled is used, another object in use holds a reference to it, causing it to not be recycled. This causes the object that should be recycled to not be recycled and stays in the heap memory, which causes a memory leak.

Common memory leaks:

1. Unexpected global variables

The way Js handles undefined variables: Undefined The variable will create a new variable in the global object. In the browser, the global object is window.

function foo(arg) { 
bar = "this is a hidden global variable"; //等同于window.bar="this is a hidden global variable"
this.bar2= "potential accidental global";//这里的this 指向了全局对象(window),
等同于window.bar2="potential accidental global"}
Copy after login

Solution: Add and enable strict mode 'use strict' in the JavaScript program to effectively avoid the above problems.

Note: Global variables used to temporarily store large amounts of data must be set to null or reassigned after ensuring that the data is processed.

2. DOM leakage

In the browser, the engines used by DOM and JS are different. DOM uses a rendering engine, while JS uses v8 engine, so using JS to operate DOM will consume more performance, so in order to reduce DOM operations, we will use variable references to cache them in the current environment. If you perform some deletion and update operations, you may forget to release the cached DOM, thus causing a memory leak

Example: Reference to uncleaned DOM elements

var refA = document.getElementById('refA');
document.body.removeChild(refA); // #refA不能回收,因为存在变量refA对它的引用。
将其对#refA引用释放,但还是无法回收#refA。
Copy after login

Solution: Set refA = null;

3. Forgotten timers and callback functions

var someResource = getData();
setInterval(function() {
    var node = document.getElementById('Node');
    if(node) {
        node.innerHTML = JSON.stringify(someResource));
    }
}, 1000);
Copy after login

Such code is very common, if the element with id is Node If removed from the DOM, the timer will still exist. At the same time, because the callback function contains a reference to someResource, someResource outside the timer will not be released.

4. Circular Reference

In the memory management environment of js, if object A has permission to access the object B, it is called object A referencing object B. The reference counting strategy is to see if the object has other objects referencing it. If no object refers to the object, then the object will be recycled.

var obj1 = { a: 1 }; // 一个对象(称之为 A)被创建,赋值给 obj1,A 的引用个数为 1  
var obj2 = obj1; // A 的引用个数变为 2  
 obj1 = 0; // A 的引用个数变为 1 
 obj2 = 0; // A 的引用个数变为 0,此时对象 A 就可以被垃圾回收了
Copy after login

But the biggest problem with reference counting is circular references.

function func() {  
    var obj1 = {};  
    var obj2 = {};  
    obj1.a = obj2; // obj1 引用 obj2  
    obj2.a = obj1; // obj2 引用 obj1  }
Copy after login

When the function is executed, the return value is undefined, so the entire function and internal variables should be recycled. However, according to the reference counting method, the number of references of obj1 and obj2 is not 0, so they are not will be recycled. So to solve this problem, you can set their values ​​to null

Summary: The above is the entire content of this article, I hope it will be helpful to everyone.

The above is the detailed content of What is a memory leak and how to fix it. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Diablo 4 memory leak issue on Windows: How to fix it Diablo 4 memory leak issue on Windows: How to fix it Apr 13, 2023 pm 09:34 PM

Diablo 4 Memory Leak Issue on Windows: 13 Ways to Fix Memory leaks in Diablo 4 can be caused by a variety of issues. The game is still in development, so issues like this are to be expected. The main cause of the memory leak appears to be the texture quality settings in Diablo 4. We recommend you to start with the first fix mentioned below and then go through the list until you manage to resolve the issue. let's start. Method 1: Set Texture Quality to Medium or Low "High" texture quality seems to be the main cause of memory leaks in Diablo 4. This appears to be an unexpected bug, as users with high-end GPUs and workstations have also reported this as a potential fix. Go to your dark

Common memory management problems and solutions in C# Common memory management problems and solutions in C# Oct 11, 2023 am 09:21 AM

Common memory management problems and solutions in C#, specific code examples are required. In C# development, memory management is an important issue. Incorrect memory management may lead to memory leaks and performance problems. This article will introduce readers to common memory management problems in C#, provide solutions, and give specific code examples. I hope it can help readers better understand and master memory management technology. The garbage collector does not release resources in time. The garbage collector (GarbageCollector) in C# is responsible for automatically releasing resources and no longer using them.

What are the causes of golang memory leaks? What are the causes of golang memory leaks? Jan 10, 2023 pm 05:45 PM

The reasons for the leak are: 1. The use of time.After(). Each time.After(duration x) will generate NewTimer(). Before the duration x expires, the newly created timer will not be GC. GC; 2. time.NewTicker resources are not released in time; 3. select blocking; 4. channel blocking; 5. applying for too many goroutines, goroutine blocking; 6. caused by slice, etc.

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.

Methods to solve the problem of memory leak location in Go language development Methods to solve the problem of memory leak location in Go language development Jul 01, 2023 pm 12:33 PM

Methods to solve the problem of memory leak location in Go language development: Memory leak is one of the common problems in program development. In Go language development, due to the existence of its automatic garbage collection mechanism, memory leak problems may be less than other languages. However, when we face large and complex applications, memory leaks may still occur. This article will introduce some common methods to locate and solve memory leak problems in Go language development. First, we need to understand what a memory leak is. Simply put, a memory leak refers to the

What are the memory leaks caused by closures? What are the memory leaks caused by closures? Nov 22, 2023 pm 02:51 PM

Memory leaks caused by closures include: 1. Infinite loops and recursive calls; 2. Global variables are referenced inside the closure; 3. Uncleanable objects are referenced inside the closure. Detailed introduction: 1. Infinite loops and recursive calls. When a closure refers to an external variable internally, and this closure is repeatedly called by external code, it may cause a memory leak. This is because each call will cause a memory leak in the memory. Create a new scope in the scope, and this scope will not be cleaned up by the garbage collection mechanism; 2. Global variables are referenced inside the closure, if global variables are referenced inside the closure, etc.

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,

What is the difference between memory leak and memory overflow? What is the difference between memory leak and memory overflow? Dec 03, 2020 pm 05:22 PM

Difference: Memory overflow means that when the program applies for memory, there is not enough memory space for it to use, and the system can no longer allocate the space you need; memory leak means that the program cannot release the applied memory space after applying for memory. , the harm of a memory leak can be ignored, but too many memory leaks will lead to memory overflow.

See all articles