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