Home > Web Front-end > JS Tutorial > An in-depth analysis of the garbage collection mechanism in JS

An in-depth analysis of the garbage collection mechanism in JS

青灯夜游
Release: 2023-03-02 19:31:13
forward
1586 people have browsed it

Basic types are stored on the stack, and reference types are stored on the heap. JavaScript automatically allocates memory when variables (objects, strings, etc.) are created, and "automatically" releases them when they are not used. The process of releasing is called garbage collection.

An in-depth analysis of the garbage collection mechanism in JS

Garbage collection strategy

Tasks that all garbage collectors need to do

  • Mark active (live) objects and inactive (non-live) objects in the space

  • Recycle or reuse the memory occupied by inactive objects

  • Memory organization to prevent the occurrence of memory fragmentation

What is a garbage object?

Generally speaking, objects that are not referenced are garbage and must be cleared. Traverse the object starting from the root.

Exceptions
If several object references form a ring and refer to each other, but the root cannot access them, these objects are also garbage and must be cleared.

What are root objects and surviving objects

The root object
has a basic set of inherently reachable values , cannot be deleted due to obvious reasons

  • Global variables window global objects, DOM document tree root objects, etc.

Live objects
A value is considered accessible if the reference or reference chain can access any other value from the root

V8 engine recycling generational recycling method

Divide the heap into the new generation and the old generation.
The new generation stores objects with short lifetimes, and the old generation stores objects with long lifetimes.

New generation garbage collector scavenge copy algorithm

Divides heap memory into two parts, one is the usage area , the space in use; the other is the free area, the space in idle state.

  • Newly added objects will be stored in the usage area. When the usage area is almost full, garbage needs to be Cleanup operations.

  • The new generation garbage collector will mark active objects objects in the use area. After the marking is completed, will copy the active objects in the use area to the free area. . Solved the problem of scattered memory blocks.

  • Clean up the space occupied by inactive objects in the usage area. Finally, the roles are reversed, the original use area becomes a new free area, and the original free area becomes a new use area.

Objects moved to the old generation

  • If an object still survives after being copied many times, it will be considered to have a long life cycle. Long objects are subsequently moved to the old generation.
  • When copying an object to the free area and occupying more than 25% of the free area, the object will be directly promoted to the old generation space. The reason is that the original free area will become a new used area, and object memory allocation will continue. If the ratio is too high, there will be too little available space for new objects.

New generation optimization parallel recycling

Full pause problem
JavaScript is a single-threaded language. Running on the main thread, the execution of the JavaScript script will be blocked during garbage collection. You need to wait for the garbage collection to complete before resuming script execution.

If a GC takes too long, it may cause page freezes.

Parallel recycling mechanism
During the execution of the garbage collector on the main thread, multiple auxiliary threads are started to perform the same recycling work at the same time.

An in-depth analysis of the garbage collection mechanism in JS

Old generation garbage collection

Problems with using the scavenge method
1. Survival objects If there are too many, the efficiency of frequently copying surviving objects will be reduced
2. Half of the space is wasted

mainly uses the mark-clear method. When the memory allocation is insufficient, use mark-organize Method

Algorithm used in the old generation garbage collection period
1. First use mark-clear to complete garbage space recovery;
2. Use mark-organize for space optimization;
3. Use optimization-incremental marking and lazy cleaning for efficiency optimization;

##Mark-clearing and marking-organizing algorithms

scavenge only copies live objects, while mark-clear only clears dead objects.


Live objects only account for a small part of the new generation, and dead objects only account for a small part of the old generation. This is why both recycling methods can be processed efficiently.

Disadvantages Too many memory fragments. If a large memory needs to be allocated, garbage collection will be triggered in advance because the remaining fragmented space is not enough to complete the allocation, and this collection is unnecessary.

-> Marking-organizing algorithm After marking the surviving objects, move the surviving objects to one end of the memory space. After the movement is completed, clear all memory outside the boundary

Optimization - Incremental Marking and Lazy Cleanup

Incremental Marking

If there are many objects and we try to traverse and mark the entire set of objects at once, Then it may take some time and there will be some delay in execution. Therefore, the engine attempts to break up garbage collection into multiple parts. Then, each part is executed separately.

V8 has optimized the old generation garbage collector, switching from full pause marking to incremental marking .
Turn a garbage collection into a short period of GC garbage collection
An in-depth analysis of the garbage collection mechanism in JS
If a black and white (survival and death) marking strategy is adopted, then the garbage collector executes an increment After recycling, the main thread is enabled after a pause to execute a piece of JavaScript code in the application. Then when the garbage collector is started again, there is black and white in the memory, and we cannot know where to go next.

Lazy Cleanup

Lazy cleanup begins after the incremental marking is completed. When the incremental marking is completed, if the current available memory is enough for us to execute the code quickly, we actually do not need to clean up the memory immediately. We can delay the cleanup process slightly and let the JavaScript script code execute first. There is no need to clean up all at once. After all inactive object memory is cleared, you can clean it one by one as needed until all inactive object memory is cleared, and then perform incremental marking

three-color marking method Pause and resume

The mark operation of the three-color marking method can be executed gradually without scanning the entire memory space each time. It can be well coordinated with incremental recycling for pause and recovery. operation, thereby reducing the total pause time

  • White: Unmarked object
  • Gray: The object itself is marked, and the reference object of the object is not marked
  • Black: Both itself and the reference object of the object (the object pointed by the arrow) are marked

An in-depth analysis of the garbage collection mechanism in JS
Starting from a group of root objects, first The root object is marked gray and pushed into the marking worksheet. When the recycler pops the object from the marking worksheet and accesses its reference object, it converts itself from gray to black and converts its next reference object. Gray

Just keep going down until there are no objects that can be marked gray, that is, there are no objects that can be reached, then all the remaining white objects are unreachable, that is Waiting for recycling.

Whether there is a gray node in the current memory will determine whether the entire mark is completed. If there is no gray node, it will directly enter the cleanup phase. If there is still a gray mark, it will continue execution directly from the gray node during recovery. Can

Write barrier

After a complete GC mark block pause, the task program is executed and the reference relationship of the object is modified. .
An in-depth analysis of the garbage collection mechanism in JS
Assume that in the first incremental segmentation, all ABCs are marked black, and then the JavaScript script is executed, B->D, to start the second incremental segmentation.

The new object D is initially white, but there are no gray objects at this time, which means that all markings are completed and cleanup needs to begin. D will be recycled during the cleanup phase. this is not right.
V8 introduces a write barrier mechanism. Once a black object references a white object, this mechanism will turn the referenced white object into gray.

Concurrent recycling
  • Parallel recycling will block the main thread
  • The incremental mark increases the total pause time, Reduce application throughput

While the main thread is executing JavaScript, the auxiliary thread can complete the garbage collection operation in the background
An in-depth analysis of the garbage collection mechanism in JS

[Recommended learning: javascript advanced tutorial

The above is the detailed content of An in-depth analysis of the garbage collection mechanism in JS. For more information, please follow other related articles on the PHP Chinese website!

source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template