Files
scriptc/tests/corpus/process-memory-usage-array-buffers.cjs
T
Chris Tate f9b024dbab Count ArrayBuffer storage in process.memoryUsage()
process.memoryUsage() reported external and arrayBuffers as 0. arrayBuffers
is now the storage of the ArrayBuffers, typed arrays, Buffers, DataViews
and SharedArrayBuffers the program holds, and external the same storage
without SharedArrayBuffers, as Node splits them. A view over existing
storage adds nothing. v8.getHeapStatistics().external_memory reads the
same figure as external.

Each ScrBytes owner records the bytes it counts in the struct's padding,
so ScrBytes stays 64 bytes and the offsets compiled code reads hold; a
static assertion pins them. Owners are counted in a per-instance counter,
because their reference counts are not atomic and they are released on
their instance's thread. Shared storage moves its owner's count to a
process-wide atomic counter, since any thread may release it.
2026-10-29 13:36:41 -05:00

42 lines
1.7 KiB
JavaScript

// process.memoryUsage() counts the storage of ArrayBuffers, typed arrays,
// Buffers, DataViews and SharedArrayBuffers in arrayBuffers, and external
// includes arrayBuffers. A view over existing storage adds nothing.
const size = 4 * 1024 * 1024;
const grew = (before, after) =>
[after.arrayBuffers - before.arrayBuffers >= size, after.external - before.external >= size];
const sample = () => process.memoryUsage();
let before = sample();
console.log(typeof before.arrayBuffers, typeof before.external, before.external >= before.arrayBuffers);
const ab = new ArrayBuffer(size);
console.log("ArrayBuffer", ab.byteLength, ...grew(before, sample()));
before = sample();
const f64 = new Float64Array(size / 8);
console.log("Float64Array", f64.byteLength, ...grew(before, sample()));
before = sample();
const buf = Buffer.alloc(size, 1);
console.log("Buffer.alloc", buf.length, ...grew(before, sample()));
before = sample();
const unsafe = Buffer.allocUnsafeSlow(size);
console.log("Buffer.allocUnsafeSlow", unsafe.length, ...grew(before, sample()));
before = sample();
const text = Buffer.from("x".repeat(size));
console.log("Buffer.from(string)", text.length, ...grew(before, sample()));
before = sample();
const sab = new SharedArrayBuffer(size);
const shared = new Int32Array(sab);
console.log("SharedArrayBuffer", sab.byteLength, shared.length, ...grew(before, sample()));
before = sample();
const views = [new DataView(ab), buf.subarray(1), new Uint8Array(f64.buffer, 8, 16)];
const after = sample();
console.log("views", views.length, after.arrayBuffers - before.arrayBuffers < size);
const all = sample();
console.log(all.arrayBuffers >= 6 * size, all.external >= all.arrayBuffers);