I am using Ojb-c, and I want to know the memory size of an object, but I got this,
NSObject *obj = [[[NSObject alloc] init] autorelease];
NSLog(@"malloc size of myObject: %zd", malloc_size(obj));
NSLog(@"size of myObject: %zd", sizeof(obj));
malloc size of myObject: 16
size of myObject: 4
I know the sizeof(obj) is 4, because the pointer size on ios 32 is 4 bytes, what is the difference?
But more than this,
@interface TestObj : NSObject
@property (nonatomic, retain) NSArray *arr;
@property (nonatomic, assign) int count;
@end
@implementation TestObj
@end
TestObj *obj2 = [[[TestObj alloc] init] autorelease];
NSLog(@"malloc size of obj2: %zd", malloc_size(obj2));
NSLog(@"size of obj2: %zd", sizeof(obj2));
malloc size of obj2: 16
size of obj2: 4
how could I know the real size of TestObj ? thanks.
The
sizeof
the object is how much space it requires for that object to be stored in memory. Themalloc_size
is how much space was actually allocated for it (for example, in a memory allocation system with fixed-size pools, you might be allocated a different amount depending on how much other memory was in use).sizeof()
is a compile-time measurement. Note thatsizeof(obj)
in your example is telling you the size of the pointer variable, not the size of the object it points to. Note that the size of an Objective-C object is not known at compile time, sosizeof
will not work for them.malloc_size()
is a runtime measurement. It tells you the size of a block allocated withmalloc
. Note thatmalloc
often rounds up, so this size may be larger than necessary. Note that some objects are not allocated withmalloc
somalloc_size()
will return zero.