@JeremyP provides an excellent link and information. Always read the fish. There is some breakdown of what time goes by and what you can do about it.
Firstly, there are many calls to objc_msgSend() to dynamically send. They can be avoided, and you will save some time (although not as much as you think. objc_msgSend() crazy optimized ), but you can bring it down by 5% by skipping it:
IMP addObject = class_getMethodImplementation([NSMutableArray class], @selector(addObject:)); NSNull *null = [NSNull null]; start = clock(); for(int i = 0; i < imax; i++) { NSMutableArray *v = [[NSMutableArray alloc] init]; for(int j = 0; j < jmax; j++) { addObject(v, @selector(addObject:), null); } [v release]; }
A lot of time is consumed with retain / release . You can avoid this (and stick with real numbers, not NSNumber ) by using a non-persistent CFMutableArray ). This will result in an add time of approximately 2x from vector .
CFArrayCallBacks cb = {0}; for(int i = 0; i < imax; i++) { CFMutableArrayRef v = CFArrayCreateMutable(NULL, 0, &cb); for(int j = 0; j < jmax; j++) { CFArrayAppendValue(v, &j); } CFRelease(v); }
The biggest cost to this is calls to memmove() (or its collector's version on Mac).
Man, NSMutableArray sure is slow. How could Apple be so stupid, right? I mean, really ... wait ... I wonder if something NSMutableArray better than vector ?
Try replacing these lines with your obvious counterparts:
v->insert(v->begin(), j); NSNumber *num = [[NSNumber alloc] initWithInt:j]; [v insertObject:num atIndex:0]; [num release];
(Yes, including creating and releasing NSNumber , not just using NSNull .)
Oh, and you can try this too to see how fast NSMutableArray and CFMutableArray really can be:
CFArrayInsertValueAtIndex(v, 0, &j);
In my tests, I get:
Vector insertions 7.83188 seconds NSArray insertions 2.66572 seconds Non-retaining 0.310126 seconds