Resident Set ¶
V8 operates memory with a structure called ‘Resident Set’. Just as the Java Virtual Machine (JVM) divides memory into several segments, it is said that memory is divided into Code, Stack, and Heap areas by the Resident Set structure. We need to know more about this part.
process.memoryUsage(). It seems that you can know the size of the Resident Set, the size of the heap, and the size of the heap being used.
Garbage Collection ¶
- Scavenge: fast, frequent but incomplete garbage collection - Mark-Sweep: slow, infrequent, but complete garbage collection
Memory Leak ¶
A ‘Memory Leak’ occurs when a specific element continues to occupy memory even though it will not be used in the future. The moment memory leak occurs and it exceeds the allocatable memory, the process will die.
The author provides code that intentionally induces a memory leak. The code is not included in this article. The more the code calls
replaceThing(), the more memory leaks occur. Looking at the function,
originalThing refers to the same object as
theThing, and this object was created when the
replaceThing() function was called before. When the current
replaceThing() function is called,
theThing refers to the newly created object.
The global object
theThing is updated every time the
replaceThing() function is called and refers to the newly created object each time. So the
originalThing, i.e. the object created by the previous
replaceThing() function call, is no longer used and must be removed from memory originally, by garbage collection.
Nevertheless, the cause of the memory leak is in the
someMethod(), a method of
replaceThing() function, can refer to
unused(), a function object located in an external function.
’theThing’ and ‘originalThing’ seem unrelated at first glance. However, the method
someMethod() owned by the object
theThing refers to the function object
unused, which in turn refers to the object
originalThing. In the end,
originalThing is not removed from memory and a memory leak occurs.