This content originally appeared on DEV Community and was authored by Muhmmad Awd
What happens when something is not needed anymore? How does the JavaScript engine discover it and clean it up?
Reachability
The main concept of memory management in JavaScript is reachability
.
There’s a base set of inherently reachable values, that cannot be deleted for obvious reasons.
For instance:
- 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.
These values are called roots.
Any other value is considered reachable if it’s reachable from a root by a reference or by a chain of references. There’s a background process in the JavaScript engine that is called garbage collector. It monitors all objects and removes those that have become unreachable.
let's dive in and understand how it's work
example
// user has a reference to the object
let user = {
name: "John"
};
and If the value of user is overwritten, the reference is lost:
Now John becomes unreachable. There’s no way to access it, but if we copied the reference from user to admin and overwritten the value
Then the object is still reachable via admin global variable.
mark-and-sweep
garbage collection algorithm is called “mark-and-sweep”
and these steps are regularly performed:
The garbage collector takes roots and “marks” (remembers) them.
Then it visits and “marks” all references from them.
- And so on until all reachable references are visited.
- All objects except marked ones are removed.
Summary
- Global variables are considered root, so be aware when you declare or reference them.
- Outgoing references do not matter. Only incoming ones can make an object reachable.
You can learn more and explore more complex examples on
JavaScript info
This content originally appeared on DEV Community and was authored by Muhmmad Awd
Muhmmad Awd | Sciencx (2023-05-02T05:10:44+00:00) Garbage collection. Retrieved from https://www.scien.cx/2023/05/02/garbage-collection/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.