JS memory management examples explained

小云云
Release: 2018-02-22 13:46:09
Original
1622 people have browsed it

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

JS memory management examples explained
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.

JS memory management examples explained

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.
JS memory management examples explained

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.
JS memory management examples explained

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

JS memory management examples explained

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.

JS memory management examples explained

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

var a, b;
a.reference = b;
b.reference = a;
Copy after login
  • Error using global variables

a = "1234567";
相当于
window.a = "1234567";
Copy after login
  • DOM element is cleared or The bound event was not cleared when deleted






Copy after login
  • Closure reference

function bindEvent() {
var obj = document.getElementById('xxx');

obj.onclick = function () {
/** 空函数*/
};

/** delete this reference */
// obj = null;
}
Copy after login
  • 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

// b是a的子dom节点, a是body的子节点
var aElement = document.getElementById("a");
var bElement = document.getElementById("b");
document.body.removeChild(aElement);
// aElement = null;
// bElement = null;
Copy after login

3.2 Excessive memory space usage

appears more in nodejs, for example:

  • Uncontrolled loop

while(1) {
// do sth
}
Copy after login
  • Excessively large array

var arr = [];
for (var i=0; i< 100000000000; i++) {
var a = {
'desc': 'an object'
}
arr.push(a);
}
Copy after login

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!

Related labels:
source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!