Memory: composed of read and write units, representing a piece of operable space management: the application, use and release of a piece of space thought to operate memory management: developers actively apply for space, use space, release space management process: application – use – release

// memory management

/ / application
let obj = {}
/ / use
obj.name = 'Tom'
/ / release
obj = null
Copy the code

The garbage collection

Memory management in JavaScript is automatic. Whenever we create an array, object, or function, we automatically allocate the corresponding memory space. Later in the program the object is considered garbage when it is no longer referenced, or when it is not fundamentally accessible. At this point, the JavaScript engine will come to work and reclaim the memory space occupied by the garbage. This is the garbage collection mechanism. Objects that can be accessed are reachable objects (references, scope chains), and the criterion for reachable objects is whether they can be found from the root. The root in JavaScript can be understood as a global variable object.

// Define a variable obj that refers to an object that occupies a memory space named Tom. The obj object refers to Tom.
// The obj object is reachable in the global execution. The obj object is reachable, which means that the Tom space is reachable
let obj = {name: 'Tom'}
// define an ali variable equal to obj. In this case, you can think of Tom space as another layer of reference, there is a reference value change
let ali = obj
// At this point, Tom space is still reachable, because ali is still in reference
obj = null
Copy the code

GC algorithm

GC is short for garbage collection mechanism. GC can find garbage in memory and free and reclaim space.

What is the garbage in the GC?

  • An object that is no longer needed in a program
function func(){
    name = 'lg'
    return `${name} is a coder`
}
func()
Copy the code
  • An object that can no longer be accessed in a program
function func(){
    const name = 'lg'
    return `${name} is a coder`
}
func()
Copy the code

What is the GC algorithm?

GC is a mechanism where the garbage collector does the work. The job is to find garbage, free up space, and reclaim space. Algorithms are the rules that work to find and recycle.

Common GC algorithms

Reference counting

Core idea: Set the number of references, determine whether the current number of references is 0 to determine whether a garbage object. When the reference relationship of an object changes, the reference counter will actively change the number of references corresponding to the current object. When the reference number is zero, THE GC starts working, reclaiming and freeing the object space in which it is located for reuse.

const user1 = {age: 11}
const user2 = {age: 22}
const user3 = {age: 33}
const nameList = [user1.age, user2.age, user3.age]
function fn(){
    const num1 = 1
    cosnt num2 = 2
}
fn()
Copy the code

In the current environment, num1 and num2 only function in the scope of fn. When fn() finishes, num1 and num2 are not found in the external global. At this point, the reference count of num1 and num2 becomes 0, and the GC starts to collect num1 and num2 as garbage. The nameList contains references to user1, user2, and user3, so they are not collected as garbage. Advantages of reference counting algorithm

  • Collect garbage as soon as it is found
  • Minimize program pauses

Disadvantages of reference counting algorithm

  • Objects referenced by a loop could not be reclaimed
  • Time consuming
function fn(){
    const obj1 = {}
    const obj2 = {}
    obj1.name = obj2
    obj2.name = obj1
    return 'lg is a coder'
}
fn()
Copy the code

When fn() is finished, its internal space will definitely involve space reclamation. For example, obj1 and obj2, which are no longer referred to globally, should have a zero reference count, but within FN obj1 and obj2 refer to each other through the name property, so their reference count is not zero, and GC cannot recycle them by reference counting algorithm.

Mark clear

Core idea: tag and remove two stages to complete tag removal algorithm will turn the whole garbage collection phase is divided into two phases, the first stage is to iterate through all the objects found active objects are marked operation, the second phase is to iterate over all clear unmarked object, it will also set the first stage of the tags to erase, facilitate the GC to work again. Through the two traversal behavior of the current garbage space for recycling, and finally to the free list for maintenance, convenient follow-up program execution. Compared with the reference counting algorithm, the marker clearing algorithm solves the problem that the object circular reference cannot be reclaimed

  • Will cause space fragmentation, not maximize the use of space
  • Garbage objects cannot be collected immediately

Tag to sort out

Tag cleaning can be seen as an enhancement to tag cleaning. In the marking phase, the operation is consistent with the marking removal, traversing all objects to find the active object for marking operation; The cleanup phase performs the cleanup, moving the object, and then the cleanup. The advantages of the tag collation algorithm reduce the fragmentation space The disadvantages of the tag collation algorithm are that garbage objects cannot be collected immediately

V8

V8 is one of the leading JavaScript execution engines.

  • V8 uses instant editing, which is fast.
  • V8 Memory upper limit.

V8 uses the idea of generational recycling to divide the memory space into the new generation storage area and the old generation storage area. The most efficient algorithm is used according to different generations to recycle different objects.

New generation object recycling implementation

The V8 memory space is divided into two parts. The small space is used to store new-generation objects. Cenozoic refers to objects that live for a short time. The recycling process adopts the copy algorithm + mark arrangement. First, the new generation of memory is divided into two equally large Spaces, the use space is From, and the free space is To. All the live objects are stored in the From space. After marking, the live objects are copied To the To space. The space is exchanged between From and To To complete the release. Promotions may occur during the copying process. Promotion is the movement of objects from the new generation to the old generation for storage. As for when a promotion is triggered? Generally, there are two criteria: the new generation surviving after one GC operation should be promoted; If the To space usage exceeds 25%, you need To move the active object To the elderly storage area for storage.

Old generation object recycling implementation

It mainly adopts the algorithm of mark clearing, mark sorting and incremental mark. Garbage space is first reclaimed using tag cleanup. When the contents of the new generation area are moved to the old generation area, the space of the old generation area is insufficient to store the objects moved by the new generation. At this time, the tag sorting operation will be triggered to optimize the space. Finally, the efficiency is optimized with the increment marker (the increment marker is to divide the whole garbage collection operation into several small segments, alternating between the program and the marker). The new generation of regional garbage collection uses space for time, while the old generation of regional garbage collection is not suitable for replication algorithm.

Standards for defining memory issues

  • Memory leak: Memory usage continues to rise
  • Memory ballooning: Performance issues exist on most devices
  • Frequent garbage collection: Analysis through memory change graphs

Several ways to monitor memory

  • Browser Task Manager
  • Timeline Records the timing diagram
  • Heap snapshot lookup for detached DOM
  • Determine if there is frequent garbage collection

    Identify frequent garbage collection methods
    • Frequent ups and downs in the Timeline
    • Frequent increase and decrease of data in task manager