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 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!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version
SublimeText3 Linux latest version
