As a NodeJS developer, I regularly want to control how much memory is used by the programs I’m creating, so I can assess my code choices and thus keep, update or totally change the way I coded some functionalities.
I try to force myself to do it as much as possible. I think the best version of code is the one that fulfills the requirements with the minimum of resource utilization.
I can do it using some NodeJS built-in functions, such as process.hrtime (https://nodejs.org/api/process.html#process_process_hrtime_time)
But this will add several lines of code and output values to the console.
I prefer to use a small NPM library that will do all the stuff for me and also present the result in a readable graphic chart.
For example, let’s say I want to check the memory utilization when populating then deleting an array (this is a very simple case just to present what can be done). Here is the small program:
const randomstring = require('randomstring')
let array=[]
for (let index = 0; index < 10000; index++) {
array[index]=randomstring.generate(32)
}
for (let index = 0; index < 10000; index++) {
array.splice(index)
}
I want now to check the memory utilization of such program. It will updated, using memuse NPM package (https://www.npmjs.com/package/memuse):
const memuse=require('memuse')
const randomstring = require('randomstring')
memuse.init('./mem.csv')
let array=[]
for (let index = 0; index < 10000; index++) {
array[index]=randomstring.generate(32)
memuse.poll()
}
memuse.tag('start deletion')
for (let index = 0; index < 10000; index++) {
array.splice(index)
memuse.poll()
}
memuse.end('./mem.svg')
In the program above, here are the explained steps:
- I loaded the memuse library
- I initialized it (memory utilization statistics will go into the mem.csv file)
- I called the memuse.poll() function each time I wanted to record the memory utilization statistics
- Just after the array is loaded and before deleting it, I added a tag to locate this step into the chart, using memuse.tag()
- Finally the memuse.end() produces the graphical chart.
I run the program and I get this nice memory utilization chart:
I hope this article will help you. Thanks.
Top comments (0)