Memory profiling
- Node.js course
- Expert
- Lesson 39/47
- 5 min
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.
Practice 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)).
Starter code
// Write the heapLabel function
// Below 1024 returns 'small', below 1048576 'medium', otherwise 'large'
// Print calls with 512 and 2097152
// write hereSample solution
function heapLabel(size) {
if (size < 1024) return 'small';
if (size < 1048576) return 'medium';
return 'large';
}
console.log(heapLabel(512));
console.log(heapLabel(2097152));Expected output
small large
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each piece to its role
| Term | Meaning |
|---|---|
heapUsed |
Heap in use |
heapTotal |
Heap allocated |
rss |
Resident set size |
external |
C++ objects |
2 What does heapLabel(2097152) return?
function heapLabel(s) {
if (s < 1024) return 'small';
if (s < 1048576) return 'medium';
return 'large';
}
heapLabel(2097152)- small
- medium
- large Correct answer
- 0
Explanation: 2097152 >= 1048576, so it returns 'large'.
3 Complete the large branch
if (size < 1024) return 'small';
if (size < 1048576) return 'medium';
return '____';
if (size < 1024) return 'small';
if (size < 1048576) return 'medium';
return 'large';
Explanation: Past the upper threshold it returns 'large'.