CodeBlanks Logo Icon CodeBlanks

Memory usage

Learn memory usage with process.memoryUsage.

process.memoryUsage()

process.memoryUsage() returns the process's memory usage as an object. It has four main fields: rss (Resident Set Size — total allocated memory), heapTotal (V8 heap total), heapUsed (V8 heap used), external (C++ objects).

These are numbers in bytes. To detect memory leaks you can log them at regular intervals. If heapUsed keeps growing you may have a leak.

Detecting memory leaks

A memory leak is when unused objects are not garbage collected. Over time heapUsed grows and the process crashes.

Detection method: log process.memoryUsage().heapUsed every second with setInterval. If it trends upward you have a leak. In Node.js you can take a heap snapshot in Chrome DevTools with the --inspect flag. This lets you visually find leaking objects.

Practice Check if heapTotal is positive

Store process.memoryUsage() in a variable. Log usage.heapTotal > 0.

Starter code

index.js
// get memory usage

// log if heapTotal is positive

Sample solution

index.js
const usage = process.memoryUsage();
console.log(usage.heapTotal > 0);

Expected output

true

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
rss Resident set
heapTotal Total heap
heapUsed Used heap
external External memory

2 Complete the method name

Question
const usage = process.____()
Answer
const usage = process.memoryUsage()

Explanation: process.memoryUsage() gives memory usage.

3 What does process.memoryUsage() return?

  • Bir dize
  • Bir Promise
  • Bellek nesnesi Correct answer
  • A number

Explanation: process.memoryUsage() returns an object with memory fields.

All lessons in Advanced