什么是一种有效且伟大的方法来比较NSArray
的所有值,其中包含floats
中的NSNumbers
,以找到最大值和最小值?
你知道如何在Objective-C中快速、准确地完成这个任务吗?
什么是一种有效且伟大的方法来比较NSArray
的所有值,其中包含floats
中的NSNumbers
,以找到最大值和最小值?
你知道如何在Objective-C中快速、准确地完成这个任务吗?
如果execution speed(不是programming speed)很重要,那么显式循环是最快的.我用execution speed0000个随机数做了以下测试:
版本1:对数组排序:
NSArray *sorted1 = [numbers sortedArrayUsingSelector:@selector(compare:)];
// 1.585 seconds
版本2:键值编码,使用"doubleValue":
NSNumber *max=[numbers valueForKeyPath:@"@max.doubleValue"];
NSNumber *min=[numbers valueForKeyPath:@"@min.doubleValue"];
// 0.778 seconds
版本3:键值编码,使用"self":
NSNumber *max=[numbers valueForKeyPath:@"@max.self"];
NSNumber *min=[numbers valueForKeyPath:@"@min.self"];
// 0.390 seconds
版本4:显式循环:
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;
}
// 0.019 seconds
版本5:块枚举:
__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;
}];
// 0.024 seconds
测试程序创建一个包含1000000个随机数的数组,然后应用所有排序
Update:我现在(希望)创建了一个更好的测试程序.完整的源代码如下:https://gist.github.com/anonymous/5356982.对数据进行排序的平均时间
Sorting 1.404 KVO1 1.087 KVO2 0.367 Fast enum 0.017 Block enum 0.021
Update 2:正如人们所看到的,快速枚举比块枚举(这里也说明了:http://blog.bignerdranch.com/2337-incremental-arrayification/)更快.
EDIT:以下是completely wrong,因为我忘了初始化用作锁的对象,因为热舔正确地注意到了这一点,所以根本没有进行同步.
This changes dramatically if you add the NSEnumerationConcurrent
option to the
block enumeration:
__block float xmax = -MAXFLOAT;
__block float xmin = MAXFLOAT;
id lock;
[numbers enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSNumber *num, NSUInteger idx, BOOL *stop) {
float x = num.floatValue;
@synchronized(lock) {
if (x < xmin) xmin = x;
if (x > xmax) xmax = x;
}
}];
现在的时机是
Concurrent enum 0.009
所以它的速度大约是快速枚举的两倍.结果可能不具有代表性