Skip to content

Instantly share code, notes, and snippets.

@zhenghaohe
Created Jun 20, 2022
Embed
What would you like to do?
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 getRandomNumericString() {
return Math.random().toString();
}
const randomKeyByType = {
"string-key": getRandomString,
"numeric-key": getRandomNumericString,
"integer-key": (max) => getRandomSmallIntegerString(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