Skip to content

Instantly share code, notes, and snippets.

@simonwhitaker
Created July 2, 2013 06:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonwhitaker/5907158 to your computer and use it in GitHub Desktop.
Save simonwhitaker/5907158 to your computer and use it in GitHub Desktop.
A simple benchmarking experiment to compare enumeration techniques in Objective-C. My results are in the comments.
#import <Foundation/Foundation.h>
void timeThis(NSString *label, NSUInteger iterations, void(^block)()) {
CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
for (NSUInteger i = 0; i < iterations; i++) {
block();
}
CFAbsoluteTime interval = CFAbsoluteTimeGetCurrent() - start;
printf("%s: %lu iterations, %.3fs\n", [label UTF8String], iterations, interval);
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSUInteger numberOfIterations = 20000;
NSUInteger numberOfElements = 5000;
NSMutableArray *strings = [NSMutableArray arrayWithCapacity:numberOfElements];
for (NSUInteger i = 0; i < numberOfElements; i++) {
[strings addObject:[NSMutableString stringWithFormat:@"Object %lu", i]];
}
timeThis(@"Fast enumeration", numberOfIterations, ^{
for (NSMutableString *string in strings) {
[string appendString:@"."];
}
});
timeThis(@"Block", numberOfIterations, ^{
[strings enumerateObjectsUsingBlock:^(NSMutableString *string, NSUInteger idx, BOOL *stop) {
[string appendString:@"."];
}];
});
timeThis(@"Block, concurrent", numberOfIterations, ^{
[strings enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSMutableString *string, NSUInteger idx, BOOL *stop) {
[string appendString:@"."];
}];
});
}
return 0;
}
@simonwhitaker
Copy link
Author

My results (MacBook Pro 2.6GHz i7):

Fast enumeration: 20000 iterations, 5.724s
Block: 20000 iterations, 10.921s
Block, concurrent: 20000 iterations, 3.324s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment