FinalizationRegistry 은 이름에서 알 수 있듯이 특정 변수가 Garbage Collecting 되었는지 확인 할 수 있는 클래스이다.
FinalizationRegistry 에 특정 변수와 cb(callback)을 등록하면, 그 변수가 GC 당할때 callback 을 실행시킨다.
const sleep = (ms) => new Promise(r => setTimeout(r, ms));
let waitingForCleanup = true;
const registry = new FinalizationRegistry((heldValue) => {
console.log(`cleanup: ${heldValue}`);
waitingForCleanup = false;
});
let foo = {};
registry.register(foo, 42);
foo = undefined; // Clear strong reference
const startTime = Date.now();
console.log('Allocating a lot of objects to try to force garbage collection');
while (waitingForCleanup) {
for (let i = 0; i < 100; i++) {
const x = new Array(100);
}
await sleep(10);
}
console.log(`foo was reclaimed after ${((Date.now() - startTime) / 1000).toFixed(1)}s`);
위 코드는 foo object 가 GC 당할때 console.log(~~) 콜백을 실행시킨다.
하지만, GC 가 진행되는 시점은 정확히 예측하기 힘들다.