What is the GC mechanism

Every time we create an entity (including undefined), memory is allocated, and the Garbage Collection mechanism cleans up useless variables when certain conditions are triggered, freeing up memory to avoid consuming too much memory and causing the system to crash

GC trigger condition

Baidu searched a lot, found that there is no more clear answer, most of the answers are back and forth copy. Go to Google a search sure enough still Google smell.Here’s the answer on StackOverflow One is triggered when the new generation is full, or when N bytes are allocated in the old generation. The new old generation will be mentioned below. The second is that the TAB is triggered when it is inactive or in the background. In addition to these two common triggers, there are several other triggers

Specific recovery mechanism

The generational recycling mechanism used in current V8 engines will be divided into new generation and old generation. Cenozoic generations usually store short-lived variables, while old generations store long-lived variables.

The new generation

In the new generation, the space will be divided into from space and to space. When the FROM space is full, the active objects in the FROM space will be transferred to the TO space. After all the transfer, the original MEMORY in the FROM space will be released, and then the two Spaces will be exchanged and repeated. When an object survives the middle generation and survives again, it is promoted to the old generation, as shown below

Another reason to be promoted to the old generation is that it is more than 25% of the new generation space, and it will also be placed in the old generation.

The old generation

In the old generation, the removal of inactive variables usually adopts the mark removal method, which will look up the reference of its reachable object from the root object and mark it as active object, then the unmarked object, that is, the object that the root object cannot access will be removed. V8 uses a new approach to address fragmentation, which moves all living objects to one side and then frees up the rest of the memory, but it is slower because of the move. Therefore, it is normal to use the mark elimination method, and only when the space is insufficient to store the new generation of promotion objects, the application of the mark arrangement method will be carried out.

Incremental marking

Since our application logic will be stopped during garbage collection, in order to reduce the execution of application logic JS, incremental marking is adopted in the marking stage of old generation objects, that is, the execution will be switched to the application logic execution first for slice marking.