A utility function to estimate the memory size of objects in JavaScript, compatible with both Node.js and browser environments.
npm install als-sizeofals-sizeof is a JavaScript utility function designed to estimate the memory size of objects, including buffers. It is compatible with both Node.js and browser environments, making it a versatile tool for memory usage estimation in various JavaScript applications.
formatBytes now is a property of sizeof
ArrayBuffer in browsers.
als-sizeof using npm:
bash
npm install als-sizeof
`
Usage
To use als-sizeof, simply import it into your JavaScript project and pass the object you want to estimate the size of:
`javascript
const sizeof = require("als-sizeof");
const obj = {
key1: "value1",
key2: 123,
key3: true,
};
const size = sizeof(obj);
console.log(Size of object: ${size} bytes);
console.log(Size of object: ${sizeof.formatBytes(size)});
`
Advanced Usage
als-sizeof also supports an advanced feature where you can pass a WeakSet as a second argument to the sizeof function. This WeakSet (referred to as objList) is used to keep track of the objects that have already been accounted for in size calculation. This is particularly useful for handling objects with circular references or when the same object instance appears multiple times in different parts of your data structure. To use this feature, simply create a WeakSet and pass it as the second argument to sizeof:
`javascript
const sizeof = require("als-sizeof");
const obj = {
key1: "value1",
key2: {
key3: "value3"
}
};
obj.key2.key4 = obj; // Circular reference
const objList = new WeakSet();
const size = sizeof(obj, objList);
console.log(Size of object: ${size} bytes);
`
Browser usage
In the browser, include the script and use it similarly for ArrayBuffer:
`html
``