Memory leak in Javascript
(BLOG STILL IN PROGRESS)
Refs
What is a memory leak ?
Memory allocated but not freed.
What causes memory leak and how to resolve
Accidental global variable
Global variable is referenced by the root node(window
or global this
), they never gets garbage collected. This applies to all its relatives - variable/objects referenced by this global variable, and relatives of these variable/objects as well. This may construct a large graph.
Example:
1 | // This will be hoisted as a global variable |
Multiple references
One object referenced by multiple objects but one of the references never gets revoked.
Closures
When a closure holds a reference to a large object in heap, it keeps the object in memory as long as the closure is in use.
Timers and events
The use of setTimeout, setInterval, Observers and event listeners can cause memory leaks when heavy object references are kept in their callbacks without proper handling.
Memory leak in Javascript