Skip to content

Instantly share code, notes, and snippets.

@anhkind
Created August 13, 2025 03:06
Show Gist options
  • Select an option

  • Save anhkind/983b1942a42c8f51548a036183c7bc7a to your computer and use it in GitHub Desktop.

Select an option

Save anhkind/983b1942a42c8f51548a036183c7bc7a to your computer and use it in GitHub Desktop.
Calculate Memory Size of a JS Object
function memorySizeOf(obj: any) {
const seen = new WeakSet<object>();
function sizeOf(value: any): number {
if (value === null || value === undefined) return 0;
const t = typeof value;
if (t === "number" ) return 8;
if (t === "boolean") return 4;
if (t === "bigint" ) return 8;
if (t === "string" ) return new TextEncoder().encode(value).length;
if (t === "function" || t === "symbol") return 0;
if (value instanceof ArrayBuffer) return value.byteLength;
if (ArrayBuffer.isView(value)) return (value as ArrayBufferView).byteLength || 0;
if (t === "object") {
if (seen.has(value)) return 0;
seen.add(value);
let total = 0;
if (Array.isArray(value)) {
for (const item of value) total += sizeOf(item);
return total;
}
for (const [k, v] of Object.entries(value)) {
total += sizeOf(k);
total += sizeOf(v);
}
return total;
}
return 0;
}
return sizeOf(obj);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment