Node.js Reference ยท node:sqlite and Runtime Services
Node.js v8.getHeapSpaceStatistics() method
Reference for v8.getHeapSpaceStatistics() in Node.js: the new, old, code and large-object spaces of the V8 heap and what each statistic tells you.
V8 splits its heap into spaces, each used for a different kind of object and collected in a different way. v8.getHeapSpaceStatistics() returns one entry per space, so you can see not just how much memory is in use, but where.
This is the tool to reach for when v8.getHeapStatistics() tells you the heap is large and you want to know whether it is short-lived garbage (new space) or long-lived data (old space).
import v8 from 'node:v8'; for (const space of v8.getHeapSpaceStatistics()) { console.log(space.space_name, space.space_used_size); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
v8.getHeapSpaceStatistics(): HeapSpaceInfo[]
Each element is an object:
| Name | Description |
|---|---|
space_name |
Name of the space, for example new_space, old_space, code_space, large_object_space. |
space_size |
Bytes currently reserved for the space. |
space_used_size |
Bytes in use. |
space_available_size |
Free bytes inside the space. |
physical_space_size |
Memory the operating system has actually committed for it. |
Returns: an array, one object per space. The exact set of spaces depends on the V8 version.
Usage notes
- New space (also called the young generation) holds freshly allocated objects. It is small and collected often and quickly; most objects die here.
- Old space holds objects that survived a few collections. Collecting it is more expensive, so a steadily growing old space is the classic signature of a memory leak.
- Code space holds compiled machine code; large object space holds objects too big for regular pages, such as huge arrays and strings.
- Do not hard-code the list of names. Look entries up by
space_nameand handle a missing one, because V8 versions add and rename spaces (for exampleshared_space,trusted_space). - Sample over time. One snapshot says little. Log
old_spaceusage every minute and look at the trend after garbage collections. - Per thread. As with other heap functions, the data is for the calling thread's isolate.
- Cost. The call walks a handful of spaces and is cheap, but do not call it in a hot loop.