When I was reading about closures in JavaScript I became curious about how garbage collection worked. Why do closures have variables that stick around. At first I thought it might be by reference, but I did some research and learned that garbage collection occurs when an object is unreachable which is not the same as an object is not referenced. In the previous algorithm, reference counting, cycles were a problem. Circular references would lead to memory leaks.
function f(){
var o = {};
var o2 = {};
o.a = o2; // o references
o2
o2.a = o; // o2 references o
return "azerty";
}
f();
The mark and sweep algorithm solves this issue.
Quote “In the first above example, after the function call returns, the 2 objects are not referenced anymore by something reachable from the global object.”
At that point they are garbage collected.
Reference: Memory Management
No comments:
Post a Comment