随着谓词的一个清晰的解决方案。但它不是更快(你说优化)。即使你重复使用谓词!
我为我的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