Skip to content

Instantly share code, notes, and snippets.

@psema4
Created January 14, 2016 21:07
Show Gist options
  • Save psema4/d81f8873add323e4891d to your computer and use it in GitHub Desktop.
Save psema4/d81f8873add323e4891d to your computer and use it in GitHub Desktop.
Rough Size of a JavaScript Object
// SOURCE: http://stackoverflow.com/a/11900218/773209
function roughSizeOfObject( object ) {
var objectList = [];
var stack = [ object ];
var bytes = 0;
while ( stack.length ) {
var value = stack.pop();
if ( typeof value === 'boolean' ) {
bytes += 4;
}
else if ( typeof value === 'string' ) {
bytes += value.length * 2;
}
else if ( typeof value === 'number' ) {
bytes += 8;
}
else if
(
typeof value === 'object'
&& objectList.indexOf( value ) === -1
)
{
objectList.push( value );
for( var i in value ) {
stack.push( value[ i ] );
}
}
}
return bytes;
}
@davidrenne
Copy link

davidrenne commented Mar 22, 2017

This function will cause an infinite loop when you have an object with a circular memory reference this will never exit. It needs something like (stack.length && loops < 100000) and never go more than 100000 keys of data before breaking out of the while loop. Whatever your max tolerance of loops are. Crashes chrome nicely. Just throw a react object with a ref in there. Those are all circular references.

There goes 4+ hours of debugging because of this beautiful infinite loop causing function.

I think 100000 keys in an object in javascript is more than enough to know the total approximate size of memory usage.

Or just scroll farther down in stack overflow answers to something like this which apparently is better to stop infinite loops

http://stackoverflow.com/a/6367736/2608143

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