Skip to content

Instantly share code, notes, and snippets.

@Tahseenm
Created May 27, 2020 10:31
Show Gist options
  • Save Tahseenm/d2daf5a7d310013a5d4ae1578eb62f2a to your computer and use it in GitHub Desktop.
Save Tahseenm/d2daf5a7d310013a5d4ae1578eb62f2a to your computer and use it in GitHub Desktop.
Is Object garbage collected
/** Determines if an object is freed
@param obj is the object of interest
@param freeFn is a function that frees the object.
@returns a promise that resolves to {freed: boolean, memoryDiff:number}
@author Steve Hanov <steve.hanov@gmail.com>
*/
function isObjectFreed(obj, freeFn) {
return new Promise(resolve => {
if (!performance.memory) {
throw new Error("Browser not supported.")
}
// When obj is GC'd, the large array will also be GCd and the impact will
// be noticeable.
const allocSize = 1024*1024*1024
const wm = new WeakMap([[obj, new Uint8Array(allocSize)]])
// wait for memory counter to update
setTimeout( () => {
const before = performance.memory.usedJSHeapSize
// Free the memory
freeFn()
// wait for GC to run, at least 10 seconds
setTimeout( () => {
const diff = before - performance.memory.usedJSHeapSize
resolve({
freed: diff >= allocSize,
memoryDiff: diff - allocSize
})
}, 10000)
}, 100)
})
}
let foo = { bar:1 }
isObjectFreed(foo, () => foo = null)
.then(result => {
document.write(`Object GCd:${result.freed}, ${result.memoryDiff} bytes freed`)
},error => {
document.write(`Error: ${error.message}`)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment