Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
calculate memory size of javascript object, it is not a accurate value!
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));
};
@shevchenkonik
Copy link

The function sizeOf doesn't work with Uint8Array and other standard types of arrays.

@sankethmandapati
Copy link

Thankyou, it works

@begoat
Copy link

begoat commented Mar 26, 2020

awesome

@sagar-gavhane
Copy link

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

@liSong5713
Copy link

   `         bytes += obj.length * 2;`  why  obj.length*2 ,it should be Buffer.byteLength(str)

@ImCityHunter
Copy link

why bytes += obj.toString().length * 2;

@0xhex
Copy link

0xhex commented May 19, 2021

i am getting error :
node:1863) UnhandledPromiseRejectionWarning: RangeError: Maximum call stack size exceeded
at Buffer.toString (buffer.js:776:46)

@kriit24
Copy link

kriit24 commented Nov 12, 2021

Im getting same error
Uncaught RangeError: Maximum call stack size exceeded

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment