function memorySizeOf(obj) { | |
var bytes = 0; | |
function sizeOf(obj) { | |
if(obj !== null && obj !== undefined) { | |
switch(typeof obj) { | |
case 'number': | |
bytes += 8; | |
break; | |
case 'string': | |
bytes += obj.length * 2; | |
break; | |
case 'boolean': | |
bytes += 4; | |
break; | |
case 'object': | |
var objClass = Object.prototype.toString.call(obj).slice(8, -1); | |
if(objClass === 'Object' || objClass === 'Array') { | |
for(var key in obj) { | |
if(!obj.hasOwnProperty(key)) continue; | |
sizeOf(obj[key]); | |
} | |
} else bytes += obj.toString().length * 2; | |
break; | |
} | |
} | |
return bytes; | |
}; | |
function formatByteSize(bytes) { | |
if(bytes < 1024) return bytes + " bytes"; | |
else if(bytes < 1048576) return(bytes / 1024).toFixed(3) + " KiB"; | |
else if(bytes < 1073741824) return(bytes / 1048576).toFixed(3) + " MiB"; | |
else return(bytes / 1073741824).toFixed(3) + " GiB"; | |
}; | |
return formatByteSize(sizeOf(obj)); | |
}; |
or
if (objClass != 'Array'){
bytes += 2 * key.length;
}
this is awesome! thanks!
why boolean is 4 bytes? Maybe you have spec link?
why boolean is 4 bytes? Maybe you have spec link?
A boolean is actually 1 byte. But alignment may cause 4 bytes to be used on a 32-bit platform (or 8 bytes on a 64-bit platform). This is an old trick that comes from the observation that allocated memory takes up at least 4 or 8 bytes, and are aligned in such a way that the least significant bit or three will be zero.
Javascript engines (for example V8) are implemented using C++. You can find documentation about the size of boolean values in C++ spec. [1]
More information:
[1] –– http://eel.is/c++draft/expr.sizeof#footnoteref-69
https://www.quora.com/In-C%2B%2B-what-is-the-size-of-type-bool/answer/Sergey-Zubkov-1?ch=10&share=2471829a&srid=lXWU
https://stackoverflow.com/questions/32733314/in-v8-how-are-primitive-types-such-as-null-undefined-and-boolean-stored-in-me
The function sizeOf
doesn't work with Uint8Array and other standard types of arrays.
Thankyou, it works
awesome
If someone looking for npm library to calculate size of an object in memory then give a try to this library: https://github.com/miktam/sizeof#readme
` bytes += obj.length * 2;` why obj.length*2 ,it should be Buffer.byteLength(str)
why bytes += obj.toString().length * 2;
i am getting error :
node:1863) UnhandledPromiseRejectionWarning: RangeError: Maximum call stack size exceeded
at Buffer.toString (buffer.js:776:46)
Im getting same error
Uncaught RangeError: Maximum call stack size exceeded
it should be:
on lines 20,21.