Created
May 27, 2020 19:58
-
-
Save keithort/acd13a2d1ba498eafa009efe3a39838f to your computer and use it in GitHub Desktop.
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
/** Determines if an object is freed | |
http://stevehanov.ca/blog/index.php?id=148 | |
@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 <[email protected]> | |
*/ | |
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