Skip to content

Instantly share code, notes, and snippets.

@vikingosegundo
Last active December 16, 2015 01:39
Show Gist options
  • Save vikingosegundo/5356670 to your computer and use it in GitHub Desktop.
Save vikingosegundo/5356670 to your computer and use it in GitHub Desktop.
fast enumeration vs. block enumeration
//
// main.m
// fastenumvsblockenum
#import <Foundation/Foundation.h>
@implementation NSMutableArray (RandomUtils)
-(void)shuffle
{
NSUInteger count = [self count];
for (NSUInteger i = 0; i < count; ++i) {
NSUInteger nElements = count - i;
NSUInteger n = (arc4random() % nElements) + i;
[self exchangeObjectAtIndex:i withObjectAtIndex:n];
}
}
@end
NSTimeInterval timeMaxMinfastenum(NSArray *array, NSUInteger repeats)
{
float xmaxFastEnum = -MAXFLOAT;
float xminFastEnum = MAXFLOAT;
NSDate *startDate = [NSDate date];
for (int i=0 ; i<repeats; ++i)
for (NSNumber *num in array) {
float x = [num floatValue];
if (x < xminFastEnum) xminFastEnum = x;
if (x > xmaxFastEnum) xmaxFastEnum = x;
}
NSTimeInterval end = [[NSDate date] timeIntervalSinceDate:startDate];
return end;
}
NSTimeInterval timeMaxMinBlockEnum(NSArray *array, NSUInteger repeats)
{
__block float xmaxFastEnum = -MAXFLOAT;
__block float xminFastEnum = MAXFLOAT;
NSDate *startDate = [NSDate date];
for (int i=0 ; i<repeats; ++i)
[array enumerateObjectsUsingBlock:^(NSNumber *num, NSUInteger idx, BOOL *stop) {
float x = [num floatValue];
if (x < xminFastEnum) xminFastEnum = x;
if (x > xmaxFastEnum) xmaxFastEnum = x;
}];
NSTimeInterval end = [[NSDate date] timeIntervalSinceDate:startDate];
return end;
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSUInteger times = 100;
NSUInteger n = 1000000;
NSMutableArray *hugeArray = [NSMutableArray arrayWithCapacity:n];
for (int i=0 ; i<n; ++i) {
[hugeArray addObject:@(i)];
}
[hugeArray shuffle];
for(NSUInteger j = 0; j< 30; ++j) {
NSTimeInterval fn, bn;
if(j % 2){
fn = timeMaxMinfastenum(hugeArray, times);
bn = timeMaxMinBlockEnum(hugeArray, times);
} else {
bn = timeMaxMinBlockEnum(hugeArray, times);
fn = timeMaxMinfastenum(hugeArray, times);
}
NSLog(@"fast enum: %f \t block enum: %f \t %@", fn, bn, (fn < bn )? @"fast enum" : @"block enum");
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment