I have a question about JavaScript garbage collection (GC).
I don't understand why only the former variable obj is GCed in the following two examples.Both of them have not been referenced to be monitored, and the timing of global.gc() execution is within the same synchronization process, so there seems to be no change.What is causing the difference?
// GC Example
hoge();
function hoge() {
letobj={}
const fr = new FinalizationRegistry(function(value){
console.log(value);
});
fr.register(obj, 'object');
obj = null;
global.gc();
}
//Example not GCed
hoge();
global.gc();
function hoge() {
letobj={}
const fr = new FinalizationRegistry(function(value){
console.log(value);
});
fr.register(obj, 'object');
obj = null;
}
Perhaps you are determining that fr
will not be GCed by the output of object
, but since fr
is the local variable of hoge()
, the callback function setting is just not propagating outside hoge()
.
When fr
is the global scope, the output reads object
.
const fr = new FinalizationRegistry(function(value){
console.log(value);
});
function hoge() {
letobj={}
fr.register(obj, 'object');
obj = null;
}
hoge();
global.gc();
FinalizationRegistry:Notes on cleanup callbacks
There are always where even implementations that normally call up callbacks are unlikely to call them:
test.js
function hoge(){
letobj={}
const fr = new FinalizationRegistry(function(value){
console.log(value);
});
fr.register(obj, 'object');
obj = null;
return fr;//return FinalizationRegistry instance
}
const_=hoge();
global.gc();
// execution result
object
© 2024 OneMinuteCode. All rights reserved.