JS memory management examples explained
JS has a complete memory processing mechanism, so we did not need to pay special attention to the implementation of this before. If the page is not fast, just refresh it and it will be fine; if the browser is stuck, restart it and it will be OK. However, with the popularity of SPA and mobile APP, and the possible implementation of PWA in the future, JS memory may become a new memory bottleneck.
1. What is a memory leak
When we decide not to use some memory anymore, due to wrong encoding, we fail to make the GC (Gabbage Collection) Correctly recycling these memories is a memory leak.
2. Memory occupancy, allocation and recycling
2.1 Memory occupancy
The memory occupied by an object is divided into direct occupied memory (Shallow Size) and total occupied memory (Retained Size).
Directly occupy memory: The memory occupied by the object itself. A typical JavaScript object has reserved memory used to describe the object and store its direct values. Generally, only arrays and strings will significantly occupy memory directly (Shallow Size). But strings and arrays often store the main data portion in renderer memory, only exposing a small wrapper object in the JavaScript object stack.
Total memory occupied: Directly occupied memory and the memory occupied by the dependent objects referenced by this reference.
Assignment and New operations will involve memory usage.
2.2 Memory allocation
Chrome V8’s garbage collection (GC) algorithm is based on Generational Collection. The memory is divided into two types, called For Young Generation (YG) and Old Generation (OG).
The so-called Young and Old are divided according to the time they occupy. The memory allocation and recycling in YG is fast and frequent, and generally exists for a short time, so it is called Young; while in OG, it is slow and occurs rarely, so it is called Old.
Because in V8, YG’s GC process will block the program, but OG’s GC will not block. So usually developers are more concerned about the details of YG.
YG is divided into two parts of space, called From and To respectively. All memory is allocated from the To space. When To is full, GC starts to be triggered. Let’s take a closer look.
At a certain moment, To has allocated memory to A, B and C. Currently, it has a small piece of memory left that has not been allocated, while all the memory of From is free.
At this time, a program needs to allocate memory for D, but the memory size required by D exceeds the unallocated size of To memory, as shown below. At this time, GC is triggered and the page stops executing.
Then From and To are swapped, that is, the original To space is marked as From, and From is marked as To. And if the live variable values (such as B) are marked, and the "garbage" (such as AC) is not marked, they will be cleared.
The live B will be copied to the To space, and the "garbage" AC will be recycled. At the same time, D will be allocated to the To space, and finally the following figure will appear. The distribution of
At this point, the entire GC is completed, and the page stops executing during this process, so it should be as fast as possible. When the value in YG survives for a long time, it will be pushed to OG. When the space of OG is full, the GC in OG will be triggered. The GC of OG will trigger the GC of YG.
Each allocation reduces the available space of To, and the program is closer to GC
YG’s GC will block the program, so the GC time should not be too long within 10ms, because frames will be lost in 16ms; GC should not be too frequent
After a certain value becomes garbage, the memory will not be released immediately. The memory occupied will only be recycled during GC.
2.2 The contents are all from references
2.3 Memory Recycling
GC Root is the root node of memory. In the browser, it is the window, and in NodeJS, it is the global object.
Traverse the graph starting from GC Root. All nodes that can be reached are called live nodes. If there is a node that cannot be reached by GC Root, then the node It is called "garbage" and will be recycled, as shown in the gray node in the figure.
As for the recycling of the root node, it is not under the control of the user.
3. Causes of memory leaks
3.1 The path to the GC root is not completely cut off
Because the path to the root node is not completely cut off, the automatic GC will not reclaim this part of the memory, causing a memory leak.
The specific reasons are:
Mutual references between objects
<span style="font-size: 14px;">var a, b;<br>a.reference = b;<br>b.reference = a;<br></span>
Error using global variables
<span style="font-size: 14px;">a = "1234567";<br>相当于<br>window.a = "1234567";<br></span>
DOM element is cleared or The bound event was not cleared when deleted
<span style="font-size: 14px;"><p id="myp"><br> <input type="button" value="Click me" id="myBtn"><br></p><br><br><script type="text/javascript"><br> var btn = document.getElementById('myBtn');<br> btn.onclick = function () {<br> document.getElementById('myp').innerHTML = 'Processing...';<br> /* 清除事件绑定 */<br> // btn.onclick = null;<br> };<br></script><br></span>
Closure reference
<span style="font-size: 14px;">function bindEvent() {<br> var obj = document.getElementById('xxx');<br><br> obj.onclick = function () {<br> /** 空函数*/<br> };<br><br> /** delete this reference */<br> // obj = null;<br>}<br></span>
When the DOM element is cleared or deleted, there are JS references in the child elements, resulting in all parent elements of the child elements not being deleted
<span style="font-size: 14px;">// b是a的子dom节点, a是body的子节点<br>var aElement = document.getElementById("a");<br>var bElement = document.getElementById("b");<br>document.body.removeChild(aElement);<br>// aElement = null;<br>// bElement = null;<br></span>
3.2 Excessive memory space usage
appears more in nodejs, for example:
Uncontrolled loop
<span style="font-size: 14px;">while(1) {<br> // do sth<br>}<br></span>
Excessively large array
<span style="font-size: 14px;">var arr = [];<br>for (var i=0; i< 100000000000; i++) {<br> var a = {<br> 'desc': 'an object'<br> }<br> arr.push(a);<br>}<br></span>
Related recommendations:
Detailed introduction to memory management in Linux
Detailed explanation of the garbage collection mechanism of php memory management (picture)
How to avoid JavaScript memory leaks and memory management techniques
The above is the detailed content of JS memory management examples explained. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

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

Golang is a powerful and efficient programming language that can be used to develop various applications and services. In Golang, pointers are a very important concept, which can help us operate data more flexibly and efficiently. Pointer conversion refers to the process of pointer operations between different types. This article will use specific examples to learn the best practices of pointer conversion in Golang. 1. Basic concepts In Golang, each variable has an address, and the address is the location of the variable in memory.

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
