Permalink
Browse files

class_getInstanceSize instead of sizeof for Objective-C

objects. changed C++ method to virtual in Performance.
  • Loading branch information...
1 parent 1b1bd17 commit 8b9e55f16824feb41e51eeafced6b9b899fcc660 @swannodette committed Nov 3, 2009
Showing with 17 additions and 7 deletions.
  1. +2 −2 Classes/Classes.m
  2. +14 −4 Performance/Classes/Array_Speed_TestViewController.mm
  3. +1 −1 Performance/Classes/MyCppObject.h
View
@@ -1,13 +1,13 @@
#import <Foundation/Foundation.h>
-#import <malloc/malloc.h>
+#import <objc/runtime.h>
#import "MyClass.h"
#import "AnotherClass.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+ NSLog(@"size of MyClass instance %d", class_getInstanceSize([MyClass class])); // note use of class_getInstanceSize over sizeof
MyClass *instanceA = [[MyClass alloc] initWithName:@"Foo"];
- NSLog(@"size of MyClass instance %d", malloc_size(instanceA)); // note use of malloc_size over sizeof
[instanceA sayHello];
NSLog(@"Sum of 4 and 5: %d", [instanceA addA:4 toB:5]);
@@ -7,7 +7,7 @@
//
#import "Array_Speed_TestViewController.h"
-
+#import <objc/runtime.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
@@ -80,16 +80,26 @@ - (IBAction) doCArray:(id)sender
- (void) allocateArrays
{
if(cArray) delete cArray;
- cArray = new MyCppObject[numberOfItems];
- [nsArray release];
- nsArray = [[NSMutableArray alloc] initWithCapacity:numberOfItems];
+
+ cArray = new MyCppObject[numberOfItems];
+
+ [nsArray release];
+ nsArray = [[NSMutableArray alloc] initWithCapacity:numberOfItems];
+
for(int i=0; i<numberOfItems; i++) {
cArray[i].f = random() * 1.0f/(RAND_MAX+1);
MyNSObject *myObj = [[MyNSObject alloc] init];
myObj.f = cArray[i].f;
[nsArray addObject:myObj];
[myObj release];
}
+
+ // if doSomething is virtual the sizes are identical
+ // if doSomething is not virtual the C++ instance is half the size
+ size_t cpp_size = sizeof(MyCppObject);
+ NSLog(@"Size of instance %d, size of array of %d C++ objects %d", cpp_size, numberOfItems, numberOfItems * cpp_size);
+ size_t obj_size = class_getInstanceSize([MyNSObject class]);
+ NSLog(@"Size of instance %d, size of array of %d Objective-C objects %d", obj_size, numberOfItems, numberOfItems * obj_size);
}
@@ -13,7 +13,7 @@ class MyCppObject {
public:
float f;
- void doSomething() {
+ virtual void doSomething() {
f++;
}

0 comments on commit 8b9e55f

Please sign in to comment.