Created
May 27, 2020 10:08
-
-
Save dmarchuk/eaa135a5af3de680f6cd816229cf9d31 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 | |
@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