On the JavaScript garbage collection

github for more resources

https://github.com/ChenMingK/WebKnowledges-Notes
online reading: https://www.kancloud.cn/chenmk/web-knowledges/1080520

Garbage collection

For garbage collection algorithm, the core idea is to determine how the memory is no longer used
relatively old saying is reference counting and mark Clear

Reference count

Reference counting algorithm defines "unused memory," the standard is very simple, is to see whether an object has a reference to it. If there are no other objects to it, indicating that the object is no longer a need.

// 创建一个对象 person,他有两个指向属性 age 和 name 的引用
var person = {
    age: 12,
    name: 'aaaa'
};
 
person.name = null // 虽然设置为null,但因为 person 对象还有指向 name 的引用,因此name 不会回收
 
var p = person
person = 1        // 原来的 person 对象被赋值为 1,但因为有新引用 p 指向原 person 对象,因此它不会被回收
p = null           // 原 person 对象已经没有引用,很快会被回收

As can be seen from the above, reference counting algorithm is a simple and effective method. But it has a fatal problem: circular references. If two objects refer to each other, even though they are no longer in use, the garbage collector will not be recovered, leading to memory leaks. For example follows

function cycle () {
    var o1 = {}
    var o2 = {}
    o1.a = o2
    o2.a = o1
    return "Cycle reference!"
}
cycle()

Clear labeling

Clear labeling algorithm "objects no longer in use" is defined as "unable to achieve the target." Simply put, the scanning start timing of the object in the memory from the root (the object is global in JS). People may arrive from the roots, they are also to be used. Starting from the roots of those objects can not be touched are marked as no longer in use, were later recovered.
As can be seen from this concept, we can not touch the object contains no reference to the concept of the object (not the object of any object reference is not accessible). But the reverse is not necessarily true.

V8 engine garbage collection

You can read the article , recently read "layman's language Node.js" Amoy to introduce garbage collection of some V8.

V8's garbage collection and memory limits

In general backend development language, there is no fundamental limit on memory usage, however, will be found in the Node can use the memory portion (64-bit system is about 1.4 GB of memory through use of JavaScript, about 32-bit system 0.7 GB). Under such restrictions, the operation will not directly result in a large memory Node object, such as a 2GB file can not be read into a character string analysis processing memory. (Stream module solves this problem)

The main cause of this problem is that the Node-based build V8, V8 is more than enough memory management mechanism in the browser application scenarios, but in the Node has limited the developers. So we need to know the V8's memory management scheme.

The object allocation V8

In V8, all JavaScript objects (object) are to be allocated through the heap, Node provides the V8 in the memory usage of View, as follows:

process.memoryUsage()
{ rss: 21434368,
  heapTotal: 7159808,
  heapUsed: 4455120,
  external: 8224 }

Which, heapTotal and heapUsed is V8 heap memory usage, the former has applied to the heap memory, which is the amount currently in use. If you have applied for allocation of free memory heap new object is not enough heap memory will continue to apply until the V8 heap size exceeds the limit is reached.
As to why the V8 to limit the size of the heap, the memory is mainly caused by garbage collection over the General Assembly cause the thread to suspend execution of JavaScript time increases, the performance and responsiveness of applications will be straight decline, this situation is not only unacceptable back-end services, front-end browser We can not accept. Therefore, in consideration of the time limit direct heap memory is a good choice.
But V8 also offers the option to let us open this restriction, Node can pass the following option when you start:

node --max-old-space-size=1700 test.js // 单位为 MB 设置老生代的内存空间
node --max-new-space-size=1024 test.js // 单位为 KB 设置新生代的内存空间

Above initialization parameters take effect when the V8, once in force can not be changed.

V8's garbage collection mechanism

V8's garbage collection policy is mainly based on generational garbage collection mechanism, in practical applications, it was found that none of the garbage collection algorithm capable of all scenarios, because the life cycle of objects of different lengths, different algorithms can only be for a particular situation It has the best effect. Thus, modern garbage collection algorithm according to the object of the survival time of the memory garbage collection different generational, and then were subjected to a more efficient algorithms for different generational memory.
In V8, the main memory into the new generation and the old generation. The target for the new generation of shorter survival time of the object, the object for the Older Generation survive longer or permanent memory of the object.

Here Insert Picture Description

Scavenge algorithm
in generational basis, the new generation garbage collection is primarily performed by Scavenge algorithm, Scavenge In a particular implementation, the main method employed Cheney.
Cheney garbage collection algorithm is an algorithm duplicated manner employed, it heap memory into two, each part of the space is called the semispace. In these two semispace space, only one is in use, the other is idle. Space in use of space is called semispace From space, idle space is called To.

Here Insert Picture Description
When we assign an object, first in the From allocate space. When starting garbage collection, checks the live objects From space, the survival of these objects will be copied to the To space, rather than survival space occupied by the object will be released.
After copying, From space, and roles To swap space occurs.

  • Scavenge drawback is that only use half of the heap memory
  • Scavenge is a typical sacrifice space for time algorithm suitable for the new generation, because the short life cycle of the new generation of objects
  • When an object is copied many times are still alive, it will be considered a long life cycle of the object, which will then be moved to the old generation, this process is called promotion

Mark-Sweep & Mark-Compact
Older Generation longer life cycle of the object, a larger proportion of live objects, V8 embodiment mainly in the old generation, and Mark-Sweep Mark-Compact combination of garbage collection
Mark-Sweep: Clear mark , mark and sweep it into two stages. All objects in the heap traversal mark phase and mark the object alive, cleared only object is not marked in the cleanup phase. Mark-Sweep biggest problem is that once marked the clear recovery of the memory space will be discontinuous state, memory fragmentation have caused subsequent memory allocation problems, such as insufficient space debris allocate a large object lead to premature triggering garbage collection.
Then there is the Mark-Compact: tags to organize, in short, after marking the completion plus a finishing stage, live objects to the end of the movement (the merger), finishing clean-up directly off the memory after the completion of the external borders.

Here Insert Picture Description
Incremental Marking
In order to avoid the application logic and JavaScript garbage collector inconsistent see the emergence of three basic garbage collection algorithms need to apply logic to pause, to be completed before the implementation of garbage collection recovery execute application logic, this behavior is called full stop (stop-the-world).
For the new generation, the full stop has little effect, but for the old generation will need to be improved.
In order to reduce the dwell time full of garbage recycling brings, V8 uses a technology incremental markings (incremental marking), presumably to split the original breath pause to complete the action for many small "steps", each done a " stepper "let JavaScript application logic performs a little while, garbage collection and application logic performed alternately until the completion of the mark phase.

Here Insert Picture Description
V8 subsequent cleanup also introduces a delay (lazy sweeping), incremental collation (incremental compaction), concurrent mark technology, interest may themselves about.

View garbage collection log

Add startup --trace_gcparameters, so that when carrying out garbage collection, garbage collection will print log information from the standard output.
Here's a sample, after the execution, the garbage collector will get all the information gc.log file:

node --trace_gc -e "var a = []; for (var i = 0; i < 1000000; i++) a.push(new Array(100));" > gc.log

By using --prof Node parameter at startup, data profiling can be performed at V8:

node --prof test.js

Guess you like

Origin www.cnblogs.com/cmk1018/p/11347571.html