在由Nsdictionary对象组成的NSARRAY中查找最大整数值



是否有任何快速有效的方法可以在NSArray中查找由NSDictionary对象组成的最大int值?我的意思是,我可以实现for周期进行,但是我正在寻找一些API函数,因为它使用相当大的数据运行,因此已经调整了最大速度。

[(int, string, string), (int, string, string), (int, string, string)]

我尝试使用valueForKeyPath,但这确实没有帮助我,因为它可以与"普通" NSARRAY对象一起使用。

出于好奇,我对valueForKeyPath:与简单迭代进行了一些比较。在我运行OS X 10.8.2的iMac Core i7上,简单的迭代大约是10m元素的速度的两倍。

这是我制作的测试程序:

#import <Foundation/Foundation.h>
#undef NDEBUG
#import <assert.h>
#import <limits.h>
#import <stdio.h>
#import <stdlib.h>
#define ELEMENTS_IN_ARRAY 10000000
NSArray *newArrayWithDictionaryElementCount(int count) {
    NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:count];
    for (int i = 0; i < count; ++i) {
        [arr addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                        [NSString stringWithFormat:@"value%d", i], @"string",
                        [NSNumber numberWithInt:rand()], @"int",
                        nil]];
    }
    return arr;
}
int maxIntValueByKeyPathInArray(NSArray *arr) {
    return [(NSNumber *)[arr valueForKeyPath:@"@max.int"] intValue];
}
int maxIntValueByIterationInArray(NSArray *arr) {
    int max = INT_MIN;
    for (NSDictionary *dict in arr) {
        int val = [(NSNumber *)[dict valueForKey:@"int"] intValue];
        if (val > max) {
            max = val;
        }
    }
    return max;
}
NSTimeInterval timeExecutionOf(void(^blockToTime)(void)) {
    NSDate *start = [NSDate date];
    blockToTime();
    return -[start timeIntervalSinceNow];
}
int main (int argc, const char *argv[]) {
    srand(time(NULL));
    @autoreleasepool {
        NSArray *arr = newArrayWithDictionaryElementCount(ELEMENTS_IN_ARRAY);
        assert(maxIntValueByIterationInArray(arr) == maxIntValueByKeyPathInArray(arr));
        (void) printf("Time by key path: %f sn", timeExecutionOf(^{ maxIntValueByKeyPathInArray(arr); }));
        (void) printf("Time by iteration: %f sn", timeExecutionOf(^{ maxIntValueByIterationInArray(arr); }));
    }
    return 0;
}

我的机器上的结果:

$ clang -fobjc-arc -framework Foundation -O4 -march=corei7 -o arraytest arraytest.m
$ ./arraytest
Time by key path: 1.809646 s
Time by iteration: 0.886023 s

我的假设是迭代解决方案已经与这些数据结构一样快。对于每个数组元素,不必进行词典查找。此外,这种定制的迭代解决方案受益于知道所有NSNumber对象都有int值;使用isGreaterThan:进行比较会有所减慢(但仍然比valueForKeyPath:更快)。任何通用图书馆方法几乎肯定会在内部产生罚款……

我现在不知道这是快速的,但是您可以使用valueForKeyPath:的内置@max操作员:

NSArray *array = @[
    @{ @"value" : @5, @"name" : @"foo"},
    @{ @"value" : @7, @"name" : @"bar"},
    @{ @"value" : @3, @"name" : @"abc"}
];
NSNumber *maximum = [array valueForKeyPath:@"@max.value"];
NSLog(@"%@", maximum);
// Output: 7

在此示例中,value是字典键,该值是NSNumber对象,因为您无法将int存储在字典中。

(请参阅"键值编码编程指南"中的收集操作员。)

更新:这绝对不是最快的解决方案,正如Arkku在他的答案中所显示的那样。

是的,有一种更好的方法来分类数组由NSDictionary组成。在给定的代码段中,它包括位置字典。每个字典对象都由名称和距离键组成。

数组看起来像:

(   
     {      name = "Electronics Store";
           distance = 9;
     },{      name = "Caffeteria Store";
          distance = 29;
    }    
)

这里的排序是根据字典的"键距离"进行的。请确保关键距离需要是一个INT值。

例如:

[detail_dict setValue:[NSNumber numberWithInt:[distance intValue]] forKey:@"distance"];

注意:它使距离作为排序的int值。

之后,只需对NSMutableArray的默认方法进行排序:代码:

 [arr_details sortUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"distance" ascending:YES]]]

最新更新