Created
July 2, 2013 06:30
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My results (MacBook Pro 2.6GHz i7):