Collection Operation Speed Tests

I wanted to see how various looping evaluation methods worked on an NSArray vs. NSMutable array.

I created an NSMutableArray with 1,000,000 NSNumber objects. I created the NSArray from [NSArray arrayWithArray:].

I ran this on my iPhone 5S.

I only tested a for(i=0; i < ; i++) vs. fast enumeration for the averaging. This is a foregone conclusion

for (i=;<;++) fast enumeration
.068, .064 .042, .042
.060, .054 .042, .043

Interestingly, for the average calculation, the fast enumeration is clearly faster than NSExpression, but for the standard deviation, NSExpression seems to nose out the fast enumeration. The valueForKeyPath is bizarrely slow. I should learn more about this, but not good for fast calculations!

fast enumeration NSExpression valueForPathKey
NSArray
average .042, .042 .078, .077 12.185, 12.46
standard Dev. .120, .119 .114, .113 N/A
sum - .048 -
min .042 .049 -
max - .048 -
median - 1.56 -
mode - 1.67 -
NSMutableArray
average .042, .043 .075, .075 12.998, 12.96
standard Dev. .118, .120 .112, .112 N/A

Contrary to my (admittedly, likely ill-informed) expectation, NSMutableArray is every bit as fast as NSArray.

in terms of code clarity: Fast Enumeration: (5-7 lines of code.)

NSMutableArray *testCalc = [[NSMutableArray alloc] initWithCapacity:1000000];
sumOfDifferencesSquared = 0;
avg = 0;
stddev = 0;

for (NSNumber *n in testCalc) avg += n.floatValue;
avg = avg/testCalc.count;
for (NSNumber *n in testCalc) sumOfDifferencesSquared += (avg - n.floatValue)*(avg - n.floatValue);
stddev = sqrtf(sumOfDifferencesSquared/testCalc.count));

NSExpression: (2 lines of code)

NSMutableArray *testCalc = [[NSMutableArray alloc] initWithCapacity:1000000];

expression = [NSExpression expressionForFunction:@"average:" arguments:@[[NSExpression expressionForConstantValue:testCalc]]];
id stddev = [expression expressionValueWithObject:nil context:nil];

for average calculations, depending on the size of the array, the difference in speed is probably worth doing the fast enumeration