Skip to content

Instantly share code, notes, and snippets.

@anhkind
Created August 13, 2025 03:06
Show Gist options
  • Save anhkind/983b1942a42c8f51548a036183c7bc7a to your computer and use it in GitHub Desktop.
Save anhkind/983b1942a42c8f51548a036183c7bc7a to your computer and use it in GitHub Desktop.

Revisions

  1. anhkind created this gist Aug 13, 2025.
    37 changes: 37 additions & 0 deletions memorySizeOf.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    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);
    }