Skip to content

Instantly share code, notes, and snippets.

@toji
Created December 30, 2022 03:58
Show Gist options
  • Save toji/4da9a73096e02aa761d0829710671330 to your computer and use it in GitHub Desktop.
Save toji/4da9a73096e02aa761d0829710671330 to your computer and use it in GitHub Desktop.
FinalizationRegistry test
let nextId = 0;
const allocatedObjects = new Map();
const refLossTimes = new Map();
let reportCount = 0;
let reportTime = 0;
const finReg = new FinalizationRegistry((id) => {
const lossTime = performance.now() - refLossTimes.get(id);
refLossTimes.delete(id);
reportCount++;
reportTime += lossTime;
console.log(`Reported GC of allocation ${id} ${lossTime}ms after the last reference was removed.`)
});
const intervalId = setInterval(() => {
// Allocate 4Mb at a time
const memoryBlock = new ArrayBuffer(1024 * 1024 * 4);
const id = nextId++;
allocatedObjects.set(id, memoryBlock);
finReg.register(memoryBlock, id);
// Lose the reference one second after creation.
setTimeout(() => {
allocatedObjects.delete(id);
refLossTimes.set(id, performance.now());
}, 1000);
}, 100);
setTimeout(() => {
clearInterval(intervalId);
let oldestLoss = performance.now();
for (let [key, lossTime] of refLossTimes.entries()) {
if (lossTime < oldestLoss) {
oldestLoss = lossTime;
}
}
console.error(`After 2 minues ${refLossTimes.size} reference losses have still been unreported, with the oldest being ${performance.now() - oldestLoss}ms ago.`);
console.error(`${reportCount} GCs were reported, with the average time from reference loss to finalizer callback being ${reportTime / reportCount}ms`);
}, 120000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment