I made tests with an array of 1000000 random numbers:
Suppose we have numbers is an array having 1000000 number object
Method 1: sort the array:
NSArray *sorted1 = [numbers sortedArrayUsingSelector:@selector(compare:)]; took 1.585 seconds
Method 2 : Key-value coding, using "doubleValue":
NSNumber *max=[numbers valueForKeyPath:@"@max.doubleValue"];
NSNumber *min=[numbers valueForKeyPath:@"@min.doubleValue"]; took 0.778 seconds
Method 3: Key-value coding, using "self":
NSNumber *max=[numbers valueForKeyPath:@"@max.self"];
NSNumber *min=[numbers valueForKeyPath:@"@min.self"]; took 0.390 seconds
Method 4: Block enumeration:
__block float xmax = -MAXFLOAT;
__block float xmin = MAXFLOAT;
[numbers enumerateObjectsUsingBlock:^(NSNumber *num, NSUInteger idx, BOOL *stop) {
float x = num.floatValue;
if (x < xmin) xmin = x;
if (x > xmax) xmax = x;
}];
took 0.024 seconds
Method 5: Explicit loop:
float xmax = -MAXFLOAT;
float xmin = MAXFLOAT;
for (NSNumber *num in numbers) {
float x = num.floatValue;
if (x < xmin) xmin = x;
if (x > xmax) xmax = x;
} took 0.019 seconds
So, if execution speed is important, then an explicit loop is the fastest.
#iOS #Girijesh #Xcode #iPhone
No comments:
Post a Comment