隨着謂詞的一個清晰的解決方案。但它不是更快(你說優化)。即使你重複使用謂詞!
我爲我的2GHz i7 MacBook Pro寫了一個小測試。解決辦法:
1.000.000次濾波的陣列:
- 每當一個新的謂詞:39.694秒
- 重用謂詞:17.784秒
- 您的代碼:2.174秒
很大的區別不是嗎?
這裏是我的測試代碼:
@implementation Test
- (void)test1
{
int x = 0;
NSArray *array = @[@"a", @"bb", @"ccc", @"dddd", @"eeeee", @"ffffff", @"ggggggg", @"hh hh", @"ii ii"];
for (int i = 0; i < 1000000; i++) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"length >= 4 AND length <= 6 AND NOT self CONTAINS ' '"];
x += [array filteredArrayUsingPredicate:predicate].count;
}
NSLog(@"%d", x);
}
- (void)test2
{
int x = 0;
NSArray *array = @[@"a", @"bb", @"ccc", @"dddd", @"eeeee", @"ffffff", @"ggggggg", @"hh hh", @"ii ii"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"length >= 4 AND length <= 6 AND NOT self CONTAINS ' '"];
for (int i = 0; i < 1000000; i++) {
x += [array filteredArrayUsingPredicate:predicate].count;
}
NSLog(@"%d", x);
}
- (void)test3
{
int x = 0;
NSArray *array = @[@"a", @"bb", @"ccc", @"dddd", @"eeeee", @"ffffff", @"ggggggg", @"hh hh", @"ii ii"];
for (int i = 0; i < 1000000; i++) {
NSMutableArray *filteredArray = [NSMutableArray array];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSString *currentWord = (NSString *)obj;
if(([currentWord length]>=4 && [currentWord length]<=6) && [currentWord rangeOfString:@" "].location == NSNotFound)
{
[filteredArray addObject:currentWord];
}
}];
x += filteredArray.count;
}
NSLog(@"%d", x);
}
感謝北斗星,這是完美的工作。你能否建議我參考一下學習謂詞相關的東西。 – ajay
Apple指南是https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/predicates.html#//apple_ref/doc/uid/TP40001798-SW1 – Wain