About Garbage Collection

Asked 2 years ago, Updated 2 years ago, 49 views

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;
}

javascript node.js

2022-09-29 21:38

2 Answers

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();


2022-09-29 21:38

FinalizationRegistry:Notes on cleanup callbacks

There are always where even implementations that normally call up callbacks are unlikely to call them:

  • When the JavaScript program shuts down entry (for instance, closing atab in a browser).
  • When the FinalizationRegistry instance is no longer reachable by JavaScript code.

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


2022-09-29 21:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.