CodeBlanks Logo Icon CodeBlanks

Heap snapshot

Learn heap snapshot and analysis.

Heap snapshot

A heap snapshot is a picture of all objects on the heap and the references between them at a given moment. Node.js lets you take V8's heap snapshot with --inspect. This is how you find memory leaks visually.

A heapSnapshot(objects) function models this: it turns each object's name and size into a string of the form 'name:size'. objects.map(o => o.name + ':' + o.size) transforms each object; .join(';') combines them into one string. Example: heapSnapshot([{name: 'a', size: 10}, {name: 'b', size: 20}]) returns 'a:10;b:20'. This model shows how a heap snapshot yields a list: each object is recorded with name and size. The output is deterministic.

The object list

A heap snapshot lists objects with their names and sizes. map turns each object into a 'name:size' string; join combines them. This produces a text representation of the snapshot.

Example: the array [{name: 'a', size: 10}, {name: 'b', size: 20}]. .map(o => o.name + ':' + o.size) gives ['a:10', 'b:20']. .join(';') yields 'a:10;b:20'. console.log(heapSnapshot([...])) prints a:10;b:20. A real heap snapshot holds far more data (references, types) but this model shows the essence — listing objects with sizes. The output is deterministic; the same objects always yield the same string.

Practice Write the heap snapshot function

Write function heapSnapshot(objects). Return objects.map(o => o.name + ':' + o.size).join(';'). Print console.log(heapSnapshot([{name: 'a', size: 10}, {name: 'b', size: 20}])).

Starter code

index.js
// Write a heapSnapshot function
// Turn each object's name and size into 'name:size'
// Join with ';' and return
// Call with [{name:'a',size:10},{name:'b',size:20}]
// write here

Sample solution

index.js
function heapSnapshot(objects) {
  return objects.map(o => o.name + ':' + o.size).join(';');
}
console.log(heapSnapshot([{name: 'a', size: 10}, {name: 'b', size: 20}]));

Expected output

a:10;b:20

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the map call

Question
return objects.____(o => o.name + ':' + o.size).join(';');
Answer
return objects.map(o => o.name + ':' + o.size).join(';');

Explanation: map turns each object into a 'name:size' string.

2 What does heapSnapshot([{name:'a',size:10}]) return?

index.js
heapSnapshot([{name:'a',size:10}])
  • 'a'
  • '10'
  • 'a=10'
  • 'a:10' Correct answer

Explanation: map produces 'a:10'; join leaves a single item as is.

3 Match each concept to its description

Term Meaning
Heap snapshot Picture of the heap
map Transforms each object
join Combines array into string
--inspect Snapshot tool

All lessons in Expert