liveBook · Manning

Process.memoryUsage()

As explained in JavaScript in Depth

A Node.js process API that returns memory-usage statistics for the running process, including heap, resident, and external memory measurements.

A memory graph can look alarming even when garbage collection is working correctly. process.memoryUsage() separates the process into five byte-valued measurements: rss, heapTotal, heapUsed, external, and arrayBuffers. Together they distinguish JavaScript heap growth from native and operating-system memory growth. section 11.1.1

Read the measurements as different layers of allocation:

  • rss is the resident set size reported by the operating system. It includes the JavaScript heap, runtime binary, native addons, thread stacks, and other touched memory. section 11.1.1
  • heapTotal is memory reserved for the managed JavaScript heap, while heapUsed is the portion occupied by live JavaScript objects and managed by the garbage collector. section 11.1.1
  • external counts native memory attached to JavaScript objects; arrayBuffers reports the ArrayBuffer and SharedArrayBuffer subset. section 11.1.1

Diagnosing a rising memory graph

Sample process.memoryUsage() during load and plot heapUsed. Normal collection produces a sawtooth whose troughs remain stable; a leak produces upward-drifting troughs. Rising heapUsed suggests retained JavaScript objects, rising external with stable heapUsed suggests Buffer or ArrayBuffer accumulation, and rising rss with both stable suggests native memory outside the engine’s management. section 11.2.1

console.log(process.memoryUsage());
 
// Prints:
{
  rss: 44732416,
  heapTotal: 5345280,
  heapUsed: 3785576,
  external: 1305759,
  arrayBuffers: 26080,
}

Inspect a representative result object to connect each metric name with its byte-valued runtime output. section 11.1.1

How JavaScript in Depth covers it

How deep it goes
Defines all five measurements and explains allocation behavior, then stops short of heap snapshots and retainer-chain analysis.
Examples
Uses byte-valued output, a ten-megabyte Buffer allocation, periodic sampling, and healthy-versus-leaking sawtooth graphs.
What it assumes
Assumes Node.js process diagnostics and basic garbage-collection terminology while distinguishing heap, external, and resident memory.
What you can do after
Diagnose memory growth by sampling metrics over time and selecting further garbage-collection or heap-analysis tools.
How it connects
Connects memory metrics to garbage collection, memory leaks, Buffers, ArrayBuffers, heap snapshots, and retainer chains.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.