I wanted to test memory usage for objects in node.js. My approach was simple: I first use process.memoryUsage().heapUsed / 1024 / 1024
to get the baseline memory. And I have an array of sizes, i.e. the number of entries in objects const WIDTHS = [100, 500, 1000, 5000, 10000]
and I plan to loop through it and create objects of that size and compare the current memory usage with the baseline memory.
function memoryUsed() {
const mbUsed = process.memoryUsage().heapUsed / 1024 / 1024
return mbUsed
}
function createObject(size) {
const obj = {};
for (let i = 0; i < size; i++) {
obj[getRandomKey()] = i;
}
return obj;
}
const SIZES = [100, 500, 1000, 5000, 10000, 50000, 100000]
const memoryUsage = {}
function fn() {
SIZES.forEach(size => {
const before = memoryUsed()
const obj = makeObject(size)
const after = memoryUsed()
const diff = after - before
memoryUsage[width] = diff
})
}
console.log(memoryUsage)
but the results didn’t look correct:
{
'100': 0.58087158203125,
'500': 0.0586700439453125,
'1000': 0.15680694580078125,
'5000': 0.7640304565429688,
'10000': 0.30365753173828125,
'50000': 7.4157257080078125,
'100000': 0.8076553344726562,
}
It doesn’t make sense. Also, since the object memoryUsage
that records the memory usage itself takes up more memory as it grows so I think it adds some overhead.
What are some of the more robust and proper ways to benchmark memory usage in node.js?