Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the size of any object in iOS?

Tags:

I was optimizing my app and wanted to know that how much is the size of the object, so that I can also show it in log.

suppose I have

NSDictionary *temp=(NSDictionary*)[Data objectAtIndex:i];  //data is defined in the .h file  

now how will I know that how much is the size of the object temp?

I tried using the variable view and in the temp section I found:

instance_size=(long int)30498656

Is the instance_size the exact size of my temp object?.

I also tried

sizeof(temp); 

but it crashed on that point. Any help...?

like image 500
Ajeet Pratap Maurya Avatar asked Nov 22 '11 07:11

Ajeet Pratap Maurya


2 Answers

The compiler knows only about the pointer, and that is why it will always return size of the pointer. To find the size of the allocated object try something like

NSLog(@"size of Object: %zd", malloc_size(myObject)); 
like image 115
Legolas Avatar answered Dec 14 '22 16:12

Legolas


First of all, I think it's clear from the above posts that the object size is given by malloc_size(myObject), as suggested by Legolas and also on the Mac OS reference manual:

The malloc_size(ptr) function returns the size of the memory block that backs the allocation pointed to by ptr. The memory block size is always at least as large as the allocation it backs, and may be larger.

But if you are interested in finding out the size of the dictionary, keep in mind the following point:

The dictionary stores key-value pairs and does not contain the object itself in the value part but just increases a retain count of the object that was to be "added" and keeps a reference of that object with itself. Now, the dictionary itself just contains the references to the various objects (with a key attached). So if by any chance you are looking for the object size of all the objects refered to by the dictionary, technically that would not be the size of the dictionary. The size of the dictionary would be the sum of the size of all the keys plus the size of all the value-references against the keys plus the size of the parent NSObject. If you are still interested in finding out the size of the refered objects as well, try iterating over the dictionary values array:

NSArray *myArray = [myDictionary allValues]; id obj = nil; int totalSize = 0; for(obj in myArray) {     totalSize += malloc_size(obj); } //totalSize now contains the total object size of the refered objects in the dictionary. 

Reference

like image 25
Parag Bafna Avatar answered Dec 14 '22 16:12

Parag Bafna