Skip to content

Instantly share code, notes, and snippets.

@jfsiii
Last active December 21, 2021 18:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jfsiii/d102c496b31d1c18782213e42fa0a497 to your computer and use it in GitHub Desktop.
Save jfsiii/d102c496b31d1c18782213e42fa0a497 to your computer and use it in GitHub Desktop.
<!doctype html>
<body>
<script>
// based on https://github.com/paulirish/memory-stats.js/blob/6fa0f359134c4668bd9b931b95156bae1073e8eb/memory-stats.js#L70-L79
function bytesToSize( bytes, nFractDigit ){
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
if (bytes === 0) return 'n/a'
nFractDigit = nFractDigit !== undefined ? nFractDigit : 0
var precision = Math.pow(10, nFractDigit)
var i = Math.floor(Math.log(bytes) / Math.log(1024))
return Math.round(bytes*precision / Math.pow(1024, i))/precision + ' ' + sizes[i]
}
function profile(fn, label) {
gc() // requires --js-flags="--expose-gc" flag
const startMem = performance.memory.usedJSHeapSize
performance.mark('start')
fn()
performance.mark('end')
// need --enable-precise-memory-info flag for accurate before/after values
const endMem = performance.memory.usedJSHeapSize
const totalMem = bytesToSize((endMem - startMem), 2)
performance.measure(`${label} ${totalMem}`, 'start', 'end')
gc() // requires --js-flags="--expose-gc" flag
}
function mapFn(v, i) { return i * 2 }
var array = Array.from({length: 1e7}, mapFn)
var string ="x".repeat(array.length)
var pojo = {length: array.length}
</script>
<script>
profile(() => array.map(mapFn), 'array.map(mapFn)')
// 76.43 MB @ 1.79 sec (no GC?)
profile(() => Array.from(array, mapFn), 'Array.from(array, mapFn)')
// 84.62 MB @ 2.36 sec (24.3ms / 1% in GC)
profile(() => Array.from(array).map(mapFn), 'Array.from(array).map(mapFn)')
// 218.05 MB @ 3.62 sec (11.1ms / 0.3% in GC)
profile(() => Array.from(string, mapFn), 'Array.from(string, mapFn)')
// 150.67 MB @ 2.25 sec (12.8 ms / 0.6% in GC)
profile(() => Array.from(string).map(mapFn), 'Array.from(string).map(mapFn)')
// 227.17 MB @ 3.71 sec (7.9 ms / 0.3% in GC)
profile(() => Array.from(pojo, mapFn), 'Array.from(pojo, mapFn)')
// 76.32 MB @ 1.07 sec (no GC?)
profile(() => Array.from(pojo).map(mapFn), 'Array.from(pojo).map(mapFn)')
// 152.62 MB @ 2.63 sec (no GC?)
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment