Created
July 2, 2023 03:17
-
-
Save H4ad/47415339ed81907c8fde7e96b9964832 to your computer and use it in GitHub Desktop.
Memory Usage from https://twitter.com/he_zhenghao
This file contains hidden or 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
function memoryUsed() { | |
gc(); | |
const mbUsed = process.memoryUsage().heapTotal / 1024 / 1024; | |
return mbUsed; | |
} | |
function getRandomString() { | |
// stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript | |
return ( | |
Math.random().toString(36).substring(2, 15) + | |
Math.random().toString(36).substring(2, 15) | |
); | |
} | |
function getRandomSmallIntegerString(max) { | |
return Math.floor(Math.random() * max).toString(); | |
} | |
function getRandomSmallInteger(max) { | |
return Math.floor(Math.random() * max); | |
} | |
function getRandomNumericString() { | |
return Math.random().toString(); | |
} | |
function getRandomNumeric() { | |
return Math.random(); | |
} | |
const randomKeyByType = { | |
"string-key": getRandomString, | |
"string-numeric-key": getRandomNumericString, | |
"numeric-key": getRandomNumeric, | |
"string-integer-key": (max) => getRandomSmallIntegerString(max), | |
"integer-key": (max) => getRandomSmallInteger(max), | |
}; | |
const sizes = [ 10000, 50000, 100000, 500000, 1000000]; | |
const memoryUsage = {'object': {}, map: {}}; | |
const createByType = { object: createObject, map: createMap}; | |
function fn() { | |
["object", "map"].forEach((type) => { | |
sizes.forEach((size) => { | |
Object.keys(randomKeyByType).forEach((randomKeyType) => { | |
gc(); | |
const getRandomKey = randomKeyByType[randomKeyType] | |
const before = memoryUsed(); | |
const obj = createByType[type](getRandomKey, size); | |
const after = memoryUsed(); | |
const diff = after - before; | |
if (!memoryUsage[type][randomKeyType]) {memoryUsage[type][randomKeyType] = {}} | |
memoryUsage[type][randomKeyType][size] = diff; | |
gc(); | |
}); | |
}); | |
}); | |
} | |
fn(); | |
console.log(memoryUsage); | |
function createObject(getRandomKey, width) { | |
const obj = {}; | |
for (let i = 0; i < width; i++) { | |
obj[getRandomKey(width)] = {}; | |
} | |
return obj; | |
} | |
function createMap(getRandomKey, width) { | |
const map = new Map(); | |
for (let i = 0; i < width; i++) { | |
map.set(getRandomKey(width), i); | |
} | |
return map; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment