什么是一种有效且伟大的方法来比较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

所以它的速度大约是快速枚举的两倍.结果可能不具有代表性

Objective-c相关问答推荐

如何使用格式化占位符本地化字符串?

为什么在目标 c 的静态上下文中允许 self

'if not' 的 Objective-C 预处理器指令

在 Xcode 中为无法识别的 Select 器创建断点

如何在 iOS SDK 中使用语音识别?

为什么我们必须在 Objective-C 中做 [MyClass class]?

如果用户禁用了应用程序的推送,是否可以进行静默远程通知?

在 Xcode 中打破 EXC_BAD_ACCESS?

如何隐藏/显示导航栏中的右键

xcode storyboard Container View - 如何访问视图控制器

如何将 .plist 文件中的数据 struct 读入 NSArray

iOS 5 不允许将下载的数据存储在 Documents 目录中?

iOS:如何将 UIViewAnimationCurve 转换为 UIViewAnimationOptions?

在 Objective-C 中,你在哪里声明一个常量?

从 UIImage 获取 Exif 数据 - UIImagePickerController

IOHIDFamily 的神秘控制台错误

获取临时目录中文件的文件路径和 URL

通过将另一个字符串重复给定次数来创建 NSString

当 UIView 框架更改时,视图内的 AVPlayer 层不会调整大小

Objective-c - CABasicAnimation 在动画后应用更改?