Skip to content

Instantly share code, notes, and snippets.

@Joaquin6
Created November 9, 2018 16:20
Show Gist options
  • Save Joaquin6/fb3aa3e9595b2fa0b4d0ca634a51ce3a to your computer and use it in GitHub Desktop.
Save Joaquin6/fb3aa3e9595b2fa0b4d0ca634a51ce3a to your computer and use it in GitHub Desktop.
A function to calculate the approximate memory usage of objects
/* Returns the approximate memory usage, in bytes, of the specified object. The
* parameter is:
*
* object - the object whose size should be determined
*/
function sizeof(object){
// initialise the list of objects and size
var objects = [object];
var size = 0;
// loop over the objects
for (var index = 0; index < objects.length; index ++){
// determine the type of the object
switch (typeof objects[index]){
// the object is a boolean
case 'boolean': size += 4; break;
// the object is a number
case 'number': size += 8; break;
// the object is a string
case 'string': size += 2 * objects[index].length; break;
// the object is a generic object
case 'object':
// if the object is not an array, add the sizes of the keys
if (Object.prototype.toString.call(objects[index]) != '[object Array]'){
for (var key in objects[index]) size += 2 * key.length;
}
// loop over the keys
for (var key in objects[index]){
// determine whether the value has already been processed
var processed = false;
for (var search = 0; search < objects.length; search ++){
if (objects[search] === objects[index][key]){
processed = true;
break;
}
}
// queue the value to be processed if appropriate
if (!processed) objects.push(objects[index][key]);
}
}
}
// return the calculated size
return size;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment