Does V8 do garbage collection on individual pieces of a scope?
Yes, it does. Only variables that are actually used inside of a closure are retained. Otherwise closure had to capture EVERYTHING that is defined in the outer scope, which could be a lot.
The only exception is if you use eval
inside of a closure. Since there is no way to statically determine, what is referenced by the argument of eval
, engines have to retain everything.
Here is a simple experiment to demonstrate this behaviour using weak module (run with --expose-gc
flag):
var weak = require('weak');var obj = { val: 42 };var ref = weak(obj, function() { console.log('gc');});setInterval(function() { // obj.val; gc();}, 100)
If there is no reference to ref
inside of the closure you will see gc
printed.