Detailed explanation of JavaScript's garbage collection mechanism

Detailed explanation of JavaScript's garbage collection mechanism

Why do we need garbage collection (GC)?

  • Programs are like people. They will produce garbage over time. Programs will also produce garbage during their operation. When too much garbage accumulates, the program will run slower.
  • The memory for strings, objects, arrays and other data in JavaScript is not fixed, and memory is dynamically allocated only when it is actually used.
  • The memory occupied by these data needs to be released when not in use so that it can be used again, otherwise the program will crash when the available memory is exhausted.

What is Garbage Collection

Garbage collection mechanism is also called Garbage Collection or GC for short. JavaScript has an automatic garbage collection mechanism that uses some recycling algorithms to find out variables or properties that are no longer used, and the JS engine periodically releases the memory space they occupy at fixed time intervals. In C/C++, programmers are required to manually perform garbage collection.

Waste Generation

When an object has no variables or properties referencing it, we will never be able to operate on the object. This object is garbage. Too many such objects will take up a lot of memory space and slow down the program.

For example:

insert image description here

Here I first declared a Person variable, which references the object {name: "江流", age: 20}. Then I pointed this Person variable to another object {name: "心猿", age: 5000}. The previously referenced object now becomes a useless object and can never be used to operate on it. This kind of object is garbage.

If there are too many garbage objects, they will take up a lot of space. If they are not released, it will affect system performance and even cause the program to crash. Therefore, garbage collection is needed to release this part of memory.

We do not need and cannot perform garbage collection in this process.

All we need is to set the objects that are no longer used to null.

Garbage Collection Strategy

The main concept of memory management in JavaScript is reachability. It roughly means that values ​​that can be accessed or used in some way need to be kept in memory, and values ​​that cannot be accessed or used need to be recycled by the garbage collection mechanism.

The garbage collection process is not performed in real time because JavaScript is a single-threaded language. Each time garbage collection is executed, the program application logic will be paused. After the garbage collection is completed, the application logic will be executed again. This behavior is called a full pause, so garbage collection is generally performed when the CPU is idle.

How to find the so-called garbage in some way is the focus of garbage collection, so the following common algorithm strategies, but here we only talk about the first two:

  1. Reference counting algorithm
  2. Mark-and-Sweep Algorithm
  3. Tag sorting
  4. Generational recycling

Reference count tags

Strategic thinking:

  • Keep track of how many times each variable value is used
  • When a variable is declared and a reference type data is assigned to the variable, the reference count of the reference type data is marked as 1.
  • If this reference type data is assigned to another variable, the number of references will be +1.
  • If the variable is overwritten by another value, the reference count is -1.
  • When the reference count of this reference type data becomes 0, the variable is no longer used and cannot be accessed. The garbage collector will destroy the reference type data with a reference count of 0 during execution and reclaim the memory space it occupies.

For example:

	let a = {
	    name: "Jiang Liu",
	    age: 20
		}; //At this point the reference count of the object is marked as 1 (a reference)
	let b = a; //At this point the object's reference count is marked as 2 (a, b references)
	a = null; //At this point the object's reference count is marked as 1 ((b reference))
	b = null; //At this point the object's reference count is marked as 0 (no variable reference)
	... //Wait for GC to reclaim this object

But this approach has a serious problem – circular references

Problems caused by circular references

In a function, the property of object A points to object B, and the property of object B points to object A. After the function is executed, the counters of objects A and B will not be 0, which affects the normal GC.

For example, the following example:

function test()
{
    let A = new Object();
    let B = new Object();
    A.pointer= B;
    B.pointer = A;
}
test();

When the properties of object A and object B reference each other, according to the reference counting strategy, their reference counts are both 2. However, after test() is executed, after the function is executed, the data objects A and B in the function scope should be destroyed by GC.

If executed multiple times, it will cause serious memory leaks.

Workaround

At the end of the function, set it to null

// Cut off the reference relationship A = null;
B = null;

Advantages and disadvantages of reference counting algorithms

advantage:

  • When the reference count is zero, garbage is immediately collected
  • Minimize program pauses

shortcoming:

  • Unable to reclaim circularly referenced objects
  • Large space cost

Mark-and-Sweep Algorithm

Core Idea

It is completed in two phases: marking and clearing.

Approximate process:

  • The garbage collector will add a mark to all variables in the memory when it is running. Assuming that all objects in the memory are garbage, all are marked as 0.
  • Then start traversing from each root object and change the nodes that are not garbage to 1
  • Clean up all garbage marked as 0, destroy and reclaim the memory space they occupy
  • Finally, change the mark of all objects in memory to 0 and wait for the next round of garbage collection.

insert image description here

Advantages and disadvantages of mark-sweep algorithm

advantage:

  • The implementation is simple. The marking situations are nothing more than two situations: hitting or not hitting. They can be marked by binary (0 and 1).
  • Ability to recycle objects with circular references
  • It is the most commonly used algorithm in the v8 engine.

shortcoming:

After garbage collection, the memory locations of the remaining objects remain unchanged, which results in discontinuous free memory space. This will cause memory fragmentation, and since the remaining space is not a whole block, memory allocation becomes a problem.

Mark-Sweep Algorithm

The Mark-Compact algorithm can effectively solve this problem. After marking, the Mark-Compact algorithm will move the objects that do not need to be cleaned up to one end of the memory, and finally clean up the memory at the boundary.

insert image description here

Garbage collection in V8 engine

  • The garbage collection of the V8 engine uses mark-sweep and generational collection methods
  • Divided into new generation and old generation

Use different algorithms for different objects:

(1) New generation: objects have a shorter survival time. New objects or objects that have only been garbage collected once.

(2) Old generation: objects survive longer. An object that has undergone one or more garbage collections.

Recycling new generation objects

The new generation objects are mainly recycled by using the copy algorithm (Scavenge algorithm) plus the mark-sweep algorithm. The specific implementation of the Scavenge algorithm mainly uses the Cheney algorithm.

Object promotion mechanism

The new generation that survives a round of GC needs to be promoted.

Recycling old generation objects

The mark-sweep, mark-compact, and incremental mark algorithms are mainly used to recycle old generation objects. The mark-sweep algorithm is mainly used, and the mark-compact algorithm is only used when memory allocation is insufficient.

  • First, use mark-sweep to complete the garbage space recovery;
  • Use mark-up to optimize space;
  • Use incremental marking to optimize efficiency;

Reference Documents:

JS garbage collection mechanism

JavaScript GC garbage collection mechanism

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of js closure and garbage collection mechanism examples
  • Detailed Example of Garbage Collection and Memory Leaks in JavaScript
  • Talk about the garbage collection mechanism in JavaScript
  • JavaScript garbage collection mechanism and memory management
  • Summary of knowledge points of new generation garbage collection in js

<<:  Several methods of calling js in a are sorted out and recommended for use

>>:  Front-end development general manual (including tools, websites, experience, etc.)

Recommend

Discussion on Web Imitation and Plagiarism

A few months after entering the industry in 2005, ...

Detailed explanation of several methods of deduplication in Javascript array

Table of contents Array deduplication 1 Double-la...

Write a formal blog using XHTML CSS

The full name of Blog should be Web log, which mea...

Vue3 Vue Event Handling Guide

Table of contents 1. Basic event handling 2. Send...

Use docker to deploy tomcat and connect to skywalking

Table of contents 1. Overview 2. Use docker to de...

How to solve the problem of MySQL query character set mismatch

Find the problem I recently encountered a problem...

Detailed graphic tutorial on installing Ubuntu 20.04 dual system on Windows 10

win10 + Ubuntu 20.04 LTS dual system installation...

Solution for mobile browsers not supporting position: fix

The specific method is as follows: CSS Code Copy ...

Detailed explanation of prototypes and prototype chains in JavaScript

Table of contents Prototype chain diagram Essenti...

Detailed explanation of viewing and setting file permissions on Mac

Preface To modify file permissions in the termina...

How to delete folders, files, and decompress commands on Linux servers

1. Delete folders Example: rm -rf /usr/java The /...

A brief introduction to MySQL storage engine

1. MySql Architecture Before introducing the stor...

Detailed explanation of the JVM series memory model

Table of contents 1. Memory model and runtime dat...