Created
December 12, 2019 18:59
-
-
Save richardscarrott/68bd9dfb30715488b56305fa96098c40 to your computer and use it in GitHub Desktop.
js-string-memory-usage
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
// node --max-old-space-size=100 --expose-gc index.js | |
const prettyBytes = require('pretty-bytes'); | |
const forceGC = () => { | |
if (global.gc) { | |
global.gc(); | |
} else { | |
console.warn('No GC hook! Start your program as `node --expose-gc file.js`.'); | |
} | |
} | |
const memoryUsage = () => { | |
forceGC(); | |
const used = process.memoryUsage(); | |
return Object.entries(used).reduce((acc, [key, value]) => `${acc}\n${key}: ${prettyBytes(value)}`, '') | |
} | |
// const randomString = () => Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); | |
const randomId = (length) => { | |
var result = ''; | |
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; | |
var charactersLength = characters.length; | |
for (var i = 0; i < length; i++) { | |
result += characters.charAt(Math.floor(Math.random() * charactersLength)); | |
} | |
return result; | |
} | |
console.log('START:', memoryUsage()); | |
let arr = []; | |
const allocate = () => { | |
// 600,000 strings === `100 MB` | |
// 600,000 numbers === '9.02 MB' | |
for (var i = 0; i < 750000; i++) { | |
arr.push(`${randomId(2)}-${randomId(13)}`); | |
} | |
} | |
const unallocate = () => { | |
arr = undefined; | |
} | |
allocate(); | |
// unallocate(); | |
console.log(arr); | |
console.log('END:', memoryUsage()); // heapUsed is the one to monitor. It will go up *and down with GC*. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment