- Published on
Garbage collection
- Authors
- Name
- Khánh
Garbage collection
Memory management in JavaScript is handled automatically by the engine. This article describes the mechanism of handling unused memory areas.
Reachability
The main concept in memory management in JavaScript is reachability.
- Reachability values refer to the ability to access or use something in some way. There are a set of rules that specify that accessible values cannot be deleted:
- The currently executing function, its local variables, and parameters.
- Other functions on the current chain of nested calls, their local variables, and parameters.
- Global variables.
- (there are some other, internal ones as well)
→ These values are called roots.
- Other values are considered reachable if they are accessible from the roots through references or a chain of references.
The garbage collector monitors all objects and deletes those that have become unreachable.
A simple example of reachability:
// user has a reference to the object
let user = {
name: "John"
};
This is the value of the global variable user referencing an object {name: "John"}
. If the value of user is changed to null, the reference is lost.
user = null;
he object {name: "John"}
becomes unreachable because there are no references to it. The garbage collector will clean up and free the memory.
Two references
Now we have two references to the same object:
// user has a reference to the object
let user = {
name: "John"
};
let admin = user;
And set
user = null;
→ The object is not deleted because admin still references the object. If the admin variable is also overwritten, the object will be deleted.
Interlinked objects
In the case where an object is linked to another object but it itself has no references, it will still be deleted.
function marry(man, woman) {
woman.husband = man;
man.wife = woman;
return {
father: man,
mother: woman
}
}
let family = marry({
name: "John"
}, {
name: "Ann"
});
Delete the reference to {name:”John”}
delete family.father;
delete family.mother.husband;
If one of the two references is deleted, it still does not meet the condition to delete {name: "John"}
.
However, if both references are deleted, {name: "John"}
will no longer have any references to it.
References from {name: "John"}
to other objects are not relevant, so {name: "John"}
is no longer reachable. The garbage collector will delete it and reclaim the memory.
Unreachable island
The entire object of the linked object will become unreachable and will be deleted and memory will be reclaimed.
family = null;