Memory leaks detection - alexanderteplov/computer-science GitHub Wiki
JavaScript is one of the so-called garbage collected languages. The main cause for leaks in garbage-collected languages is unwanted references.
Most garbage collectors use an algorithm known as mark-and-sweep.
- The garbage collector builds a list of "roots". Roots usually are global variables to which a reference is kept in code. In JavaScript, the "window" object is an example of a global variable that can act as a root.
- All roots are inspected and marked as active (i.e. not garbage). All children are inspected recursively as well. Everything that can be reached from a root is not considered garbage.
- All pieces of memory not marked as active can now be considered garbage. The collector can now free that memory and return it to the OS.
Modern garbage collectors improve on this algorithm in different ways, but the essence is the same: reachable pieces of memory are marked as such and the rest is considered garbage.
Unwanted references are are variables kept somewhere in the code that will not be used anymore and point to a piece of memory that could otherwise be freed.
- Accidental global variables
- Forgotten timers or callbacks
- Out of DOM references
- Closures
- Pieces of strings pointed to huge strings, which are considered removed
Chrome DevTools Memory tab.
You can see the current usage of memory, make a snapshot, profile memory.