In the Node example below, we are logging the heapUsed
property that's returned from process.memoryUsage()
, and we divide this value by 1000, giving us the amount of allotted memory heap in kilobytes that we used to run this process.
console.log(`${process.memoryUsage().heapUsed / 1000}kb`)
// output: 2994.304kb
If we add a comment before the console log, we can see the heapUsed
value go up. Our code, including comments, has an effect on memory used during the process.
//12345
console.log(`${process.memoryUsage().heapUsed / 1000}kb`)
// output: 2994.312kb
It's a little more interesting than that, though. If we add one more character, nothing changes:
//123456
console.log(`${process.memoryUsage().heapUsed / 1000}kb`)
// output: 2994.312kb
Why is that?
Well, it seems that, for every eight characters in our code, we need to allot another 8 bytes of heap memory.
In the comment above, we had reached this tipping point with //12345
. With the additional character added in //123456
, we're now dipping into memory that was already allotted, and so Node doesn't need to allot any more memory for this extra character.
If we append a string of 8 characters to //12345
, we can see our heap usage allot an additional 8 bytes once again.
//1234512345678
console.log(`${process.memoryUsage().heapUsed / 1000}kb`)
// output: 2994.32kb
We've reached another tipping point, and Node had to allot more memory. If we remove just one character, Node again doesn't need the additional 8 bytes.
//123451234567
console.log(`${process.memoryUsage().heapUsed / 1000}kb`)
// output: 2994.312kb
This probably won't matter for a lot of cases, but it goes to show that minification and getting rid of commented out "code graveyards" can help reduce package size as well as improve memory usage.