I thought iterating through Blocks is faster than enumeration and in some case it does. However with this simple example where I have a data array and I am creating multiple arrays using different iterating approaches and the results are not something that I was expecting.
An explanation would he helpful.
NSMutableArray *dataArray =[[[NSMutableArray alloc] init] autorelease];
NSMutableArray *mArray1 = [[[NSMutableArray alloc] init] autorelease];
NSMutableArray *mArray2 = [[[NSMutableArray alloc] init] autorelease];
NSMutableArray *mArray3 = [[[NSMutableArray alloc] init] autorelease];
NSDate *dt1 = [NSDate date];
for (int j=0; j<10000000;j++)
{
[dataArray addObject:[NSNumber numberWithInt:j]];
}
NSDate *dt2 = [NSDate date];
int cnt = [dataArray count];
//Using normal for loop
for (int k=0; k<cnt;k++)
{
[mArray1 addObject:[dataArray objectAtIndex:k]];
}
//Using Fast Enumeration
NSDate *dt3 = [NSDate date];
for (NSNumber *num in dataArray)
{
[mArray2 addObject:num];
}
//Enumerating using Blocks
NSDate *dt4 = [NSDate date];
[dataArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[mArray3 addObject:obj];
}];
NSDate *dt5 = [NSDate date];
NSLog(@"Time taken to create the data array %f",[dt2 timeIntervalSinceDate:dt1]);
NSLog(@"Time taken to iterate using normal for loop %f",[dt3 timeIntervalSinceDate:dt2]);
NSLog(@"Time taken to iterate using fast enumeration %f",[dt4 timeIntervalSinceDate:dt3]);
NSLog(@"Time taken to iterate using blocks %f",[dt5 timeIntervalSinceDate:dt4]);
//Time taken to create the data array 0.383750
//Time taken to iterate using normal for loop 0.309719
//Time taken to iterate using fast enumeration 0.278467
//Time taken to iterate using blocks 0.526629