Memory Management in JavaScript Part-3
Wednesday, May 10th, 2017
Task Scheduler in Blink Rendering Engine:
To ensure responsiveness Chrome is shipped with a task scheduler that enables prioritization of latency sensitive tasks, it tracks if the system is busy and it also has information on other tasks that are to be performed according to their urgency.
Since Chrome manages to sustain 60 FPS for most use cases therefore it has time period of 16.6 ms. Chrome uses this time period to complete frame rendering and input tasks. If Chrome completes the frame rendering and input tasks before 16.6 ms time then it will stay idle until the start of next period. This idle time is the key when learning about 'generational garbage collector' in Chrome. The task scheduler can estimate when there will be idle time in the system which helps V8 engine perform garbage collection. The idle task will have a deadline set by the task scheduler. This deadline is the time scheduler expects system to be idle.
Fig 1.0 Task Scheduler Timing Diagram
Generational Garbage Collector:
Fig 2.0 Heap Overview
The 'generational garbage collector' in V8 has the JavaScript heap split into 'Young Generation' and 'Old Generation'.
Young Generation:
The young generation has newly allocated objects. Since the objects in young generation are mostly short lived so the garbage collector performs smaller garbage collection tasks in this generation. These smaller garbage collection tasks are called 'scavenges'. The younger generation is additionally split into two semi-spaces. The newer objects are allocated to the 'active semi-space' and when it becomes full the 'scavenge' operation moves the objects to the other semi-space. Fig 3.0 show the young generation split into two semi spaces. Objects that were initially moved from from semi-space 1('active semi-space') to semi-space 2 will be promoted to old generation in the next 'scavenge' operation.
Fig 3.0 Young Generation Semi-spaces
Old Generation:
When the old generation grows beyond a derived limit the garbage collector performs major garbage collection operation on the old generation while utilizing an optimized 'Mark and Sweep' algorithm. Because marking the heap in old generation can be time consuming the V8 engine can incrementally mark objects in under 5 ms time. Finally using dedicated sweeper threads memory is freed which was initially allocated to objects in the old generation.
Fig 4.0 Overview of Garbage Collection