Garbage collector JavaScript Trash collector
JavaScript uses a garbage collection mechanism to automatically manage memory. Garbage collection is a double-edged sword, and the advantage is that it can greatly simplify the memory management code of the program, reduce the burden on the programmer, and reduce the memory leak caused by the long running time. But using garbage collection means that the programmer will have no control over the memory. ECMAScript does not expose the interface of any garbage collector. We can't force it to be garbage collected or interfere with memory management
Memory management issues
In the browser, the Chrome V8 engine instance has a life cycle that is not very long (who has nothing to do with a page open for days and months) and runs on the user's machine. If a memory leak is unfortunate, it only affects an end user. And regardless of how much memory this V8 instance consumes, eventually the memory is freed when the page is closed, with little or no management necessary (not necessarily for some large web applications that do not need to manage memory). But if you use node as the server, you need to focus on memory problems, once the memory leaks, over time the entire service will be paralyzed (the server does not restart frequently)
There are limitations to Chrome's memory limits
Chrome limits the memory limit you can use (64 bits is 1.4gb,32 bit 1.0GB), which means you won't be able to manipulate some large memory objects directly.
Why limit
Chrome limits the size of the memory, ostensibly because V8 was originally designed as a browser's JavaScript engine and is unlikely to experience a lot of memory, and deep-seated reasons are limited by the V8 garbage collection mechanism. Because V8 needs to ensure that the JavaScript application logic is different from what the garbage collector sees, V8 blocks JavaScript application logic when it performs garbage collection until the end of the garbage collection and then re-executes the JavaScript application logic, which is known as a "full pause" (Stop-the-world). If V8 heap memory for 1.5GB,V8 to do a small garbage collection needs more than 50ms, do a non-incremental garbage collection even more than 1 seconds. In this way, the browser will lose the user's response within 1s, causing the phenomenon of suspended animation. If animated, the animation's presentation will also be significantly affected.
The heap composition of Chrome V8
The heap of V8 is not just composed of Laosheng and Cenozoic, which can be divided into several different areas:
* Cenozoic Memory Area: Most of the objects are allocated here, this area is very small, but the garbage back is very frequent.
* Laosheng: Belongs to the Laosheng generation, which contains most of the objects that may have pointers to other objects, and most of the objects promoted from the new generation will be moved here
* Laosheng Data area: belongs to the Laosheng generation, where only the original data objects are saved, these objects do not have pointers to other objects
* Large Object area: This is where the volume exceeds the size of other objects, each object has its own memory, garbage collection does not move large objects
* Code Area: The Code object, which is the object containing the JIT instruction, is assigned here. The only memory area that has execute permissions
* Cell area, attribute cell area, map area: Store cell, attribute cell and map, each area is the same size element, simple structure
Each zone is comprised of a set of memory pages, which are the smallest units of V8 request memory, except for large memory pages in the larger object area, where the memory pages are 1MB in size and aligned in 1MB. Memory pages In addition to the objects that are stored, there is a header that contains metadata and identity information, and a bitmap area that is used to mark which objects are active objects. In addition, each memory page has a slot buffer allocated separately in the other memory area, which contains a set of objects that may point to other objects stored on the page. The garbage collector will only be garbage collected for the Cenozoic memory area, Laosheng, and the Laosheng data area
How the Chrome V8 garbage collection mechanism determines what is recycled
How to determine which memory needs to be reclaimed and which memory does not need to be recycled is the most basic issue that needs to be addressed during the garbage collection period. We can assume that an object is a live object if and only if it is pointed to by a root object or another live object. The root object is always a live object, which is the object referenced by the browser or V8. Objects that are pointed to by local variables also belong to the root object, because their scope objects are treated as root objects. The global object (in node, Global, window in the browser) is a natural root object. Dom elements in the browser also belong to the root object
How to identify pointers and data
The garbage collector needs to face a problem, it needs to decide which is the data, which is the pointer. Because many garbage collection algorithms move objects in memory (compact, reduce memory fragmentation), it is often necessary to rewrite the pointer
There are currently three ways to identify pointers:
1. Conservatism: If all the words on the heap are considered pointers, then some data will be mistaken for pointers. So some false pointers that are actually numbers are mistaken for pointing to an active object, causing a memory leak (the object pointed to by the dummy pointer may be a dead object, but there is still a pointer pointing to it-this false pointer points to it) and we cannot move any memory area.
2. Compiler hint method: If it is a static language, the compiler can tell us the exact location of pointers in each class, and once we know which class the object is instantiated from, we can know all the pointers in the object. This is how the JVM implements garbage collection, but this is not suitable for dynamic languages such as JS
3. Tag pointer method: This method needs to reserve one at the bottom of each word to mark whether the field is a pointer or data. This approach requires compiler support, but it's easy to implement and performs well. This is the way V8 is used. The V8 stores all the data in 32bit width, with the lowest one remaining at 0, while the minimum two bits of the pointer are 01
Recycling strategy of V8
There are many algorithms in the evolution of the automatic garbage collection algorithm, but because of the different life cycle of different objects, no algorithm is applicable to all cases. So V8 uses a generational recycling strategy that divides memory into two generations: the Cenozoic and the Laosheng. The Cenozoic object is a short-lived object, and the objects in the Laosheng generation are objects that live longer or reside in memory. Different garbage collection algorithms are used to improve the efficiency of garbage collection in the Cenozoic and Laosheng generation respectively. Objects are initially assigned to the Cenozoic, and when objects in the Cenozoic meet certain conditions (which are described later), they are moved to the Laosheng generation (promotion)
V8 Generational Memory
By default, the V8 engine in 64-bit environments has a new generation memory size of 32MB, Laosheng memory size of 1400MB, and 32 bits in half, 16MB and 700MB, respectively. The maximum reserved space for V8 memory is 1464MB (64-bit) and 732MB (32-bit), respectively. The specific formula is 4*reserved_semispace_space_ + max_old_generation_size_ that the Cenozoic consists of two blocks reserved_semispace_space_ , each 16MB (64-bit) or 8MB (32-bit)
Characteristics of Cenozoic Cenozoic
Most of the objects are assigned here, the area is small but the garbage is very frequent. It is very easy to allocate memory in the Cenozoic, so we just need to save a pointer to the memory area and constantly increment it according to the size of the new object. When the pointer reaches the end of the Cenozoic memory area, there is a cleanup (just clean up the Cenozoic)
New generation of garbage collection algorithm
The Cenozoic uses the scavenge algorithm for recycling. In the implementation of scavenge algorithm, the Cheney algorithm is mainly used.
Cheney algorithm is a garbage collection algorithm which is implemented by means of replication. It divides the memory into one, and each part of the space is called Semispace. Of these two semispace, one is in use and the other is idle. The Semispace space in use is called the From space, and the space in the idle state is called the to space, and when we allocate the object, we first allocate it in the From space. When the garbage collection algorithm is started, the surviving objects in the From space are checked, and the surviving objects are copied into the to space (which is condensed after the copy is completed), while the space occupied by the inactive objects is freed. The role of the From space and to space is swapped after the copy is complete. That is, in the process of garbage collection, it is by copying the surviving objects between two semispace. It is easy to see that when using the Cheney algorithm, half of the memory is empty. But because of the new generation is very small, so wasted memory space is not big. And because most of the objects in the Cenozoic are inactive objects, the proportion of active objects that need to be copied is very small, so its time efficiency is very ideal. The process of copying is based on the idea of BFS (breadth-first traversal), from the root object, the breadth first to traverse all reachable objects
The specific implementation process is generally the case:
Start the loop by copying all objects from the from space that are reachable from the root object to the to area, and then maintaining pointers scanptr and allocationptr for the two to extents, pointing to the active object that is about to be scanned and where the memory is about to be allocated for the new object. Each round of the loop finds the object that the current scanptr points to, and determines where each pointer inside the object points. We don't have to think about it if we point to the Laosheng generation. If you point to the from zone, we need to copy the object from the from area to the to area, and the exact location of the copy is the location pointed to by Allocationptr. After the copy is complete, the pointer inside the Scanptr object is modified to the address where the new Copy object resides, and the Allocationptr is moved. If all the pointers inside an object are processed, the scanptr moves forward and into the next loop. If Scanptr and allocationptr meet, it means that all objects have been copied, and the rest of the from area can be treated as garbage and can be cleaned up.
For a chestnut (and a space), if there is a reference similar to the following:
+----- A对象 |根对象----+----- B对象 ------ E对象 | +----- C对象 ----+---- F对象 | +---- G对象 ----- H对象 D对象
Before the execution of the scavenge, this appearance
+---+---+---+---+---+---+---+---+--------+| A | B | C | D | E | F | G | H | |+---+---+---+---+---+---+---+---+--------+
Then first copy the ABC object that the root object can reach to the to area, and the to area becomes this way:
allocationPtr ↓ +---+---+---+----------------------------+| A | B | C | |+---+---+---+----------------------------+ ↑scanPtr
Next go into the loop, scan scanptr The object of a, and find that it has no pointer, so scanptr move, and become the following
allocationPtr ↓ +---+---+---+----------------------------+| A | B | C | |+---+---+---+----------------------------+ ↑ scanPtr
Next we scan the B object and find that it has a pointer to the E object, and the E object is in the from area, then we need to copy the E object to the point where allocationptr refers and move the allocationptr pointer:
allocationPtr ↓ +---+---+---+---+------------------------+| A | B | C | E | |+---+---+---+---+------------------------+ ↑ scanPtr
All the pointers in the B object have been copied, so move the scanptr:
allocationPtr ↓ +---+---+---+---+------------------------+| A | B | C | E | |+---+---+---+---+------------------------+ ↑ scanPtr
The C object is then scanned, and the C object has two pointers, each pointing to the F object and the G object, and all in the from area, first copying the F object to the to area:
allocationPtr ↓ +---+---+---+---+---+--------------------+| A | B | C | E | F | |+---+---+---+---+---+--------------------+ ↑ scanPtr
Then copy the G object to the to area
allocationPtr ↓ +---+---+---+---+---+---+----------------+| A | B | C | E | F | G | |+---+---+---+---+---+---+----------------+ ↑ scanPtr
So the pointer inside the C object has been copied and moved Scanptr:
allocationPtr ↓ +---+---+---+---+---+---+----------------+| A | B | C | E | F | G | |+---+---+---+---+---+---+----------------+ ↑ scanPtr
Scan the E,f object one after the other, and find that there are no pointers, move the scanptr:
allocationPtr ↓ +---+---+---+---+---+---+----------------+| A | B | C | E | F | G | |+---+---+---+---+---+---+----------------+ ↑ scanPtr
Scans the G object, discovers that there is a pointer to the H object, and the H object is in the from area, copies the H object to the to area, and moves the allocationptr:
allocationPtr ↓ +---+---+---+---+---+---+---+------------+| A | B | C | E | F | G | H | |+---+---+---+---+---+---+---+------------+ ↑ scanPtr
After completion because there is no other pointer to the G object, and the H object does not have pointer movement Scanptr:
allocationPtr ↓ +---+---+---+---+---+---+---+------------+| A | B | C | E | F | G | H | |+---+---+---+---+---+---+---+------------+ ↑ scanPtr
At this point scanptr and allocationptr coincide, indicating the end of replication
You can compare the results of the from and to areas after the copy is complete:
//From区+---+---+---+---+---+---+---+---+--------+| A | B | C | D | E | F | G | H | |+---+---+---+---+---+---+---+---+--------+//To区+---+---+---+---+---+---+---+------------+| A | B | C | E | F | G | H | |+---+---+---+---+---+---+---+------------+
D object is not copied, it will be recycled as garbage
Write barrier
If an object in the Cenozoic has only one pointer to it, and this pointer is in the Laosheng generation, how can we tell if this new generation of objects survives? To solve this problem, you need to set up a list to record all Laosheng objects pointing to the new generation of objects. Every time a Laosheng object points to a new generation of objects, we record them.
Promotion of objects
When an object has survived many new generations of cleanup, it means that it has a longer life cycle and will be moved to the Laosheng generation, which is called the promotion of the object. There are two criteria for specific movement:
1. When the object is copied from the From space to the to space, it checks its memory address to see if the object has undergone a new generation of cleanup, and if so, it is copied to the Laosheng generation, otherwise copied to the to space
2. When the object is copied from the From space to the to space, if the to space has been used more than 25%, then this object is copied directly to the Laosheng generation
Characteristics of the Laosheng generation of Laosheng
Most of the objects saved by the Laosheng generation are objects with long life cycles or even resident memory, and the Laosheng consumes more memory
Garbage collection algorithm for Laosheng generation
Laosheng uses a lot of memory (64 bits is 1.4gb,32 bit 700MB), if using the scavenge algorithm, waste half of space does not say, copy such a large amount of memory consumption time will be quite long. So the scavenge algorithm is obviously not suitable. V8 's garbage collection strategy in the Laosheng generation is combined with mark-sweep and mark-compact
Mark-sweep (Mark Clear)
Tag cleanup is divided into two stages: Mark and clear. During the tagging phase, you need to traverse all objects in the heap and mark those that are alive and then into the purge phase. In the purge phase total, only objects that are not marked are purged. Because the mark clears only the dead object, and the death object occupies a small proportion in the Laosheng generation, so the efficiency is high
One problem with tag cleanup is that once you have a clear tag, the memory space is often discontinuous and a lot of memory fragmentation occurs. If the subsequent need to allocate an object that requires more memory space, if all of the memory fragmentation is not enough, it will make V8 unable to complete this assignment, triggering garbage collection ahead of time.
Mark-compact (marker finishing)
Tagging is just to solve the problem of memory fragmentation caused by markup cleanup. Mark Grooming is modified on the basis of the Mark Purge, turning its purge phase into a tightening extreme. During the process, the living object is moved to a section of the memory area, and the memory outside the boundary is cleared directly after the move is completed. The process of tightening involves moving objects, so efficiency is not too good, but it guarantees that no memory fragmentation will be generated
Algorithm Ideas
Mark Sweep and Mark grooming are divided into two stages: Mark stage, purge or crunch stage
During the tagging phase, all active objects on the heap are flagged. Each memory page has a bitmap to mark the object, and each bit in the bitmap corresponds to a word in the memory page. This bitmap needs to occupy a certain amount of space (32 bits under 3.1%, 64 bits is 1.6%). Another two bits are used to mark the state of the object, a total of three (so two bits)--white, gray, black:
* If an object is a white object, it has not yet been discovered by the garbage collector
* If an object is a gray object, it has been discovered by the garbage collector, but its adjacency object has not been fully processed
* If an object is a black object, it means that his step is discovered by the garbage collector, and its adjacency objects are all processed.
If the object in the pair is treated as a forward graph with pointers as edges, the core of the markup algorithm is depth-first search. At initial time, the bitmap is empty and all objects are white objects. Objects arriving from the root object will be shaded in gray and placed in a separate double-ended queue. Each cycle of the tagging phase, the garbage collector takes an object from the double-ended queue and turns it into a black object, turns its Adjacency object to Gray, and then puts its adjacency object in a double-ended queue. If the double-ended queue is empty or if all objects become black objects, the end. Particularly large objects may be fragmented during processing to prevent a double-ended queue overflow. If a double-ended queue overflows, the object will still become a gray object, but will not be placed in the queue, which will cause its adjacency object to not be turned into a gray object. So when the double-ended queue is empty, all objects need to be scanned, and if there are still gray objects, they are re-placed in the queue for processing. After the tag ends, all objects should be black or white, white objects will be garbage, waiting to be released
Both the purge and crunch phases reclaim memory in memory pages
When cleared, the garbage collector scans continuously stored dead objects, turns them into free space, and saves them in a list of free space. This list is often used by the scavenge algorithm to allocate memory for promoted objects, but is also used by the compact algorithm to move objects
The crunch algorithm attempts to consolidate the fragmented pages together to free up memory. Because the objects on the page are moved to a new page, some pages need to be reassigned. The approximate process is to assign a memory page to each active object in the target fragment page, copy the object to the past, and write a new memory address on the object in the fragmented page. The old address of the object is then recorded in the move-out process, and after the move-out ends, V8 iterates through the addresses of all the old objects it records and updates them to the new address. Because pointers are also recorded between different pages during the tagging process, these pointers are also updated at this point. If a page is very active, as there are too many pointers to be logged, the address record skips it until the next garbage collection is processed
Use tag cleanup and labeling together
The Laosheng generation of Chrome V8 uses tag cleanup and tagging, mainly using the tag cleanup algorithm, which is used when space is not sufficient to allocate objects promoted from the new generation.
On the garbage collection mechanism in Chrome V8 engine