Find large javascript objects (crashing your app on iphone safari)
If you've ever wondered what the size of your objects and subelements are, here is a script to show you just that. I ran into a problem with using ember.js on iphone safari where memory is limited to 5 or 10MB and the page was crashing. I wanted to find out where we were using a lot of memory and the following code will show the problem areas.
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( i in value ) {
stack.push( value[ i ] );
}
}
}
return bytes;
}
function printMemUsage(object, threshold) {
var size;
var at_least = (typeof threshold == 'undefined' ? 0 : threshold)
for (element in object) {
size = roughSizeOfObject(object[element]);
if(size > at_least) {
console.log(element + ":" + size);
}
}
}
you can call it as follows:
printMemUsage(MyApp, 1000)
activityFeedController:83012
ActivityListView:1110178
MoreActivityView:1110178
ActivityFeedView:1110178
ActivityStatsView:3432
Written by Bashir Eghbali
Related protips
3 Responses
Clever, thanks for sharing!
over 1 year ago
·
I'm flattered.
over 1 year ago
·
@tomwrong looks like you had initially published the object sizing code. I want to make sure to give you the credit for it:
http://stackoverflow.com/questions/1248302/javascript-object-size/11900218#11900218
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ember.js
Authors
ryrych
11.69K
michalbryxi
6.707K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#