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!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor