Node.js
Memory profiling
Learn memory profiling and heap analysis.
Memory profiling
Memory profiling inspects a Node.js process's heap usage. process.memoryUsage() gives the key metrics: heapUsed, heapTotal, rss and external. If these grow over time, you may have a leak.
A heapLabel(size) function models this analysis: below 1024 it returns 'small', below 1048576 'medium', otherwise 'large'. heapLabel(512) returns 'small', heapLabel(2097152) returns 'large'. This sorts memory size into three buckets; real profilers (heap snapshot, --inspect) give detailed object graphs. This model lets you quickly see which size range a bottleneck falls into.
Heap labels
Sorting heap size into three buckets makes profiling output quick to read. 'small' is healthy, 'medium' needs watching, 'large' may need action. These labels summarize a real profiler's output.
Example: heapLabel(512) returns 'small'; heapLabel(50000) returns 'medium'; heapLabel(2097152) returns 'large'. Three thresholds (1024, 1048576 and above) draw the split. In real profiling a heap snapshot shows every object type and retained bytes. This simple model shows you the range fast; then you can drill into the detail.
Exercise Write the heap label function
Write function heapLabel(size). Add if (size < 1024) return 'small';, if (size < 1048576) return 'medium'; and return 'large';. Print console.log(heapLabel(512)) and console.log(heapLabel(2097152)).
Show example solution
function heapLabel(size) {
if (size < 1024) return 'small';
if (size < 1048576) return 'medium';
return 'large';
}
console.log(heapLabel(512));
console.log(heapLabel(2097152));
Test yourself
-
Match each piece to its role
- heapUsed
- Heap in use
- heapTotal
- Heap allocated
- rss
- Resident set size
- external
- C++ objects
-
What does heapLabel(2097152) return?
function heapLabel(s) {
if (s < 1024) return 'small';
if (s < 1048576) return 'medium';
return 'large';
}
heapLabel(2097152)
Show answer
large — 2097152 >= 1048576, so it returns 'large'.
-
Complete the large branch
if (size < 1024) return 'small';
if (size < 1048576) return 'medium';
return '____';
Show answer
if (size < 1024) return 'small';
if (size < 1048576) return 'medium';
return 'large';
Next lesson: Benchmark