Home > Article > Web Front-end > Understand the garbage collection mechanism in JavaScript
Recommended tutorial: "JavaScript Video Tutorial"
I recently saw some review of interviews, and many of them were asked to talk about it by the interviewer. JS garbage collection mechanism. To be honest, the interviewer will ask this question, which means that he has recently seen some related articles about JS garbage collection mechanism, and for the sake of B, he will ask it incidentally.
Recently I saw a foreign article talking about JS garbage collection. I thought it was explained clearly, so I translated it. I hope it will be helpful to you.
Memory management in JavaScript is performed automatically and invisible. We create primitive types, objects, functions... all of which require memory.
What happens when something is no longer needed? How does the JavaScript engine discover and clean it up?
The main concept of memory management in JavaScript is Accessibility.
Simply put, "reachability" values are those that are accessible or usable in some way and are guaranteed to be stored in memory.
1. There is a basic set of inherently reachable values that cannot be deleted for obvious reasons. For example:
Local variables and parameters of the local function
Variables and parameters of other functions on the current nested call chain
Global variables
There are also some other internal
These values called root.
2. A value is considered accessible if the reference or reference chain can access any other value from the root.
For example, if there is an object in a local variable, and that object has a property that references another object, the object is considered reachable, and those it refers to are also reachable, detailed Examples are as follows.
There is a background process in the JavaScript engine called Garbage Collector, which monitors all objects and deletes those that are inaccessible.
The following is the simplest example:
// user 具有对象的引用 let user = { name: "John" };
The arrow here represents an object reference. Global variable "user"
refers to object {name: "John"}
(for the sake of brevity, we name it John). John's "name"
property stores a primitive type, so it is drawn into the object.
If the value of user
is overwritten, the reference is lost:
user = null;
Now John becomes unavailable The state is reached, there is no way to access it, there is no reference to it. The garbage collector will discard the John data and free the memory.
Now let us assume that we copy the reference from user
to admin
:
// user具有对象的引用 let user = { name: "John" }; let admin = user;
Now if we do the same thing:
user = null;
The object is still accessible via the admin
global variable, so it's in memory. If we also overwrite admin
, then it can be released.
Now look at a more complex example, the family object:
function marry (man, woman) { woman.husban = man; man.wife = woman; return { father: man, mother: woman } } let family = marry({ name: "John" }, { name: "Ann" })
Functionmarry
By giving two objects each other references to "marriage" them and return a new object containing both objects.
Resulting memory structure:
So far, all objects are accessible.
Now let us delete both references:
delete family.father; delete family.mother.husband;
It is not enough to delete only one of these two references because all objects are still accessible of.
But if we remove both of these, then we can see that John no longer has an incoming reference:
Output references don't matter. Only the passed in object makes the object accessible, therefore, John is now inaccessible and all inaccessible data will be removed from memory.
After garbage collection:
It is possible that the entire interconnected object becomes inaccessible and is removed from memory Delete in.
The source object is the same as above. Then:
family = null;
The picture in the memory becomes:
This example illustrates how important the concept of accessibility is.
Obviously, John and Ann are still linked together, both have incoming references. But this is not enough.
The "family" object has been unlinked from the root and there are no longer references to it, so the entire block below becomes unreachable and will be deleted.
The basic garbage collection algorithm is called "Mark-Sweep" and the following "garbage collection" steps are performed periodically:
The garbage collector takes the roots and "marks" (remembers) them.
It then accesses and "tags" all references from them.
Then it accesses the marked objects and marks their references. All accessed objects are remembered so that the same object is not accessed twice in the future.
And so on until there are unvisited references (accessible from the root).
All objects are deleted except marked objects.
For example, the object structure is as follows:
We can clearly see that there is an "unreachable block" on the right. Now let's see how the "mark and clear" garbage collector handles it.
The first step is to mark the roots
Then mark their references
And references to descendants:
#Objects that are now inaccessible in the process are considered inaccessible and will be deleted:
This is how garbage collection works. The JavaScript engine applies many optimizations to make it run faster without affecting execution.
Some optimizations:
Generational recycling - Objects are divided into two groups: "new objects" and "old objects". Many objects appear, complete their work and end quickly, they are quickly cleaned up. Those who live long enough become "old" and are rarely examined.
Incremental Recycling - If there are many objects and we try to traverse and mark the entire set of objects at once, it may take some time and in the execution There will be some delay. Therefore, the engine attempts to break up garbage collection into multiple parts. Then, each part is executed separately. This requires extra markers to track changes, so there are lots of tiny delays, rather than big delays.
Idle Time Collection - The garbage collector only runs when the CPU is idle to reduce possible impact on execution.
1) Ask what is garbage
Generally speaking, objects that are not referenced are garbage. It means to be cleared. There is an exception. If several object references form a ring and refer to each other, but the root cannot access them, these objects are also garbage and must be cleared.
2) How to check garbage
One algorithm is the mark-clear algorithm. If you want to talk about different algorithms, you can refer to here.
A more in-depth explanation V8 Journey: Garbage Collector
For more programming-related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of Understand the garbage collection mechanism in JavaScript. For more information, please follow other related articles on the PHP Chinese website!