Fix heap snapshots memory usage stats. Introduce estimateDirectMemoryUsageOf function in "bun:jsc" (#15790)

This commit is contained in:
Jarred Sumner
2024-12-16 20:16:23 -08:00
committed by Kai Tamkun
parent f2063ffe87
commit d8043f9a5c
55 changed files with 1093 additions and 99 deletions

View File

@@ -771,3 +771,28 @@ console.log(obj); // => { foo: "bar" }
```
Internally, [`structuredClone`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) and [`postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) serialize and deserialize the same way. This exposes the underlying [HTML Structured Clone Algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) to JavaScript as an ArrayBuffer.
## `estimateDirectMemoryUsageOf` in `bun:jsc`
The `estimateDirectMemoryUsageOf` function returns a best-effort estimate of the memory usage of an object in bytes, excluding the memory usage of properties or other objects it references. For accurate per-object memory usage, use `Bun.generateHeapSnapshot`.
```js
import { estimateDirectMemoryUsageOf } from "bun:jsc";
const obj = { foo: "bar" };
const usage = estimateDirectMemoryUsageOf(obj);
console.log(usage); // => 16
const buffer = Buffer.alloc(1024 * 1024);
estimateDirectMemoryUsageOf(buffer);
// => 1048624
const req = new Request("https://bun.sh");
estimateDirectMemoryUsageOf(req);
// => 167
const array = Array(1024).fill({ a: 1 });
// Arrays are usually not stored contiguously in memory, so this will not return a useful value (which isn't a bug).
estimateDirectMemoryUsageOf(array);
// => 16
```