Object Size Calculator

2.6.5 · active · verified Sun Apr 19

The `object-sizeof` library provides an approximation of the memory footprint of a JavaScript object in bytes. Currently at stable version 2.6.5, the package sees active maintenance with minor releases addressing types and bug fixes, as evidenced by recent updates from v2.6.1 to v2.6.4. It distinguishes itself by employing separate underlying implementations for Node.js (utilizing `Buffer.from` on stringified objects) and browser environments (using a recursive stack-based approach). A key feature is its expanded support for a wide array of built-in and complex types including Map, Set, BigInt, Function, and Typed Arrays. Unlike some alternatives, `object-sizeof` aims for robustness by returning -1 for common error scenarios such as circular references or unrecognizable TypedArray objects, preventing exceptions or infinite loops, rather than throwing errors. It also ships with TypeScript types for improved developer experience.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates calculating the approximate size of various JavaScript objects, including primitive types, complex structures like Map, Set, BigInt, Typed Arrays, functions, and showcases handling of circular references.

import sizeof from 'object-sizeof';

// Basic object
const obj1 = { id: 1, name: 'Test Object', data: [10, 20, 30] };
console.log(`Size of basic object: ${sizeof(obj1)} bytes`);

// Complex object with various types
const complexObj = {
  str: 'hello world!',
  num: 123.456,
  bool: true,
  arr: [1, 'two', { key: 'value' }],
  map: new Map([['a', 1], ['b', 2]]),
  set: new Set([1, 2, 3]),
  bigInt: BigInt(9007199254740991),
  func: () => { console.log('I am a function'); },
  typedArray: new Uint8Array([10, 20, 30, 40])
};
console.log(`Size of complex object: ${sizeof(complexObj)} bytes`);

// Object with a circular reference (will return -1)
const circularObj: any = { a: 1 };
circularObj.b = circularObj;
console.log(`Size of circular object: ${sizeof(circularObj)} bytes (expected -1 due to circularity)`);

// Test with a simple number and string
console.log(`Size of number 12345: ${sizeof(12345)} bytes`);
console.log(`Size of string "hello": ${sizeof("hello")} bytes`);

view raw JSON →