I've been playing around with the JavaScript package https://www.npmjs.com/package/object-sizeof. Just executing a .js-file with node in the console.
This is the test-object:
var someObject = {
myName: "Sarah",
myNumber: 141414141414,
mySport:"Cross Country Skiing",
myCar: {
type: "VW",
wheels: 4,
doors: 5,
},
};
The calculation within https://github.com/miktam/sizeof/blob/master/index.js#L23 made sense to me. It seemed logic to iterate over all the properties, check their types and add up the values. The result for my test object is 228 bytes.
But the main entry point for the package is https://github.com/miktam/sizeof/blob/master/indexv2.js#L62. Here the object just gets stringified, buffered and counted. The result for my test object is 118 bytes.
Quite a difference.
Can someone explain to me which one is more accurate and why? Or may be it has been explained somewhere and I just haven't found it yet, when please add a link.
Thanks.
The first method (index.js
) iterates over all the properties of the object and adds up their sizes based on their types. This method may be more accurate but also more expensive in terms of performance and memory.
The second method (indexv2.js
) simply converts the object to a JSON string, creates a buffer from it and returns its length. This method may be faster and simpler but also less accurate because it does not account for the overhead of the JSON format and the buffer encoding.
You may also want to just use Object.keys(obj)
, which returns the number of own enumerable properties of the object, and .length
. This method does not depend on any external library and works on any modern browser.
// This function takes an object as a parameter and returns the size of data in bytes
function calculateObjectSize(obj) {
// Initialize a variable to store the total size
let totalSize = 0;
// Get the keys of the object
let keys = Object.keys(obj);
// Loop through each key
for (let key of keys) {
// Get the value of the key
let value = obj[key];
// Check the type of the value
if (typeof value === "string") {
// If the value is a string, add its length to the total size
totalSize += value.length;
} else if (typeof value === "number") {
// If the value is a number, add 8 bytes to the total size
totalSize += 8;
} else if (typeof value === "boolean") {
// If the value is a boolean, add 4 bytes to the total size
totalSize += 4;
} else if (typeof value === "object" && value !== null) {
// If the value is an object and not null, recursively call the function and add the result to the total size
totalSize += calculateObjectSize(value);
}
// Ignore other types of values such as undefined, function, symbol, etc.
}
// Return the total size
return totalSize;
}