Node's global object process
has a really cool helper function called memoryUsage()
that helps measure (you guessed it) memory usage.
Some of the below code is taken and modified from Valentino Gagliardi's blog article on inspecting memory usage in Node.js.
const MB_DIVISOR = 1_000_000
const memoryUsage = process.memoryUsage()
console.log('memoryUsage', memoryUsage)
for (const [key, value] of Object.entries(memoryUsage))
console.log(`${key} ${value / MB_DIVISOR}mb`)
/* output:
memoryUsage {
rss: 19365888,
heapTotal: 3784704,
heapUsed: 2994680,
external: 325663,
arrayBuffers: 9914
}
rss 19.365888mb
heapTotal 3.784704mb
heapUsed 2.99468mb
external 0.325663mb
arrayBuffers 0.009914mb
*/
In the above example, rss
(Resident Set Size) represents the amount of memory that was allocated to run the Node process, in this case roughly 19mb.
memoryUsage()
provides a few metrics in the returned object. Here's how the Node process
docs defines these properties:
heapTotal
andheapUsed
refer to V8's memory usage.external
refers to the memory usage of C++ objects bound to JavaScript objects managed by V8.rss
, Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the process, including all C++ and JavaScript objects and code.arrayBuffers
refers to memory allocated forArrayBuffers
andSharedArrayBuffers
, including all Node.js Buffers. This is also included in theexternal
value. When Node.js is used as an embedded library, this value may be0
because allocations forArrayBuffers
may not be tracked in that case.
Using process.memoryUsage()
is a topic I'd like to touch on in a variety of scenarios in future gists. There are many topics here that require some research. Just to name a few:
- How Node / v8 uses stacks and the heap to manage memory
- Garbage Collection in JavaScript
- Comparison of Garbage Collection algorithms like mark & sweep
- Using WeakMaps, WeakRefs, and WeakSets, and measuring their implementations with
process.memoryUsage()
- v8's memory management
- Chromium's memory snapshot feature, and how it ties into v8 (and how it compares to
process.memoryUsage()
)