Created
December 30, 2022 03:58
-
-
Save toji/4da9a73096e02aa761d0829710671330 to your computer and use it in GitHub Desktop.
FinalizationRegistry test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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