function

jsc.heapStats

function heapStats(): HeapStats;

Returns statistics about the JavaScript heap, including a count of the live objects of each type. See HeapStats for what each field measures.

Counting walks the whole heap, so this is much slower than heapSize. To find out what is leaking, compare objectTypeCounts from before and after the code you suspect, calling fullGC before each snapshot so that garbage that has not been collected yet does not show up in the difference.

import { fullGC, heapStats } from "bun:jsc";

fullGC();
const before = heapStats().objectTypeCounts;
await runSuspectedLeak();
fullGC();
const after = heapStats().objectTypeCounts;
for (const [type, count] of Object.entries(after)) {
  const delta = count - (before[type] ?? 0);
  if (delta > 0) console.log(type, "+" + delta);
}

Referenced types

interface HeapStats

Statistics about the JavaScript heap, returned by heapStats. Sizes are in bytes.

heapSize and objectCount only count the objects that survived the most recent garbage collection, while objectTypeCounts includes everything currently allocated, so call fullGC before taking a snapshot you intend to compare.

  • extraMemorySize: number

    Memory owned by objects in the heap but allocated outside of it, such as the contents of strings and ArrayBuffers. Included in both heapSize and heapCapacity.

  • globalObjectCount: number

    Number of global objects in the heap: one for the main script, plus one for each node:vm context.

  • heapCapacity: number

    Memory the heap has reserved for holding objects, plus extraMemorySize. At least heapSize; the difference is space that new objects can be allocated into without growing the heap.

  • heapSize: number

    Size of the objects that survived the most recent garbage collection, plus extraMemorySize. The same number heapSize returns.

  • objectCount: number

    Number of cells that survived the most recent garbage collection. Every garbage-collected allocation is a cell: objects, strings, functions, and JavaScriptCore's internal structures alike.

  • objectTypeCounts: Record<string, number>

    Number of live cells of each type, keyed by JavaScriptCore's name for the type: JavaScript classes such as Object, Array, Promise, and Function, engine-internal types such as Structure and FunctionExecutable, and string for primitive strings. Ordered from most to least common; types with no live instances are omitted.

    Unlike objectCount, this includes cells allocated since the last garbage collection.

  • protectedGlobalObjectCount: number

    How many of the global objects are protected by native code.

  • protectedObjectCount: number

    Number of cells that native code has protected from being garbage collected. getProtectedObjects returns them.

  • protectedObjectTypeCounts: Record<string, number>

    Like objectTypeCounts, but counting only the cells included in protectedObjectCount.