用于初始化 NSCompoundPredicate 的数组中子谓词的顺序是否会影响效率?
示例:
NSString * str = [self getAStr];
NSManagedObject * mo = [self getAMo];
NSString * fmt = @"(stringAttribute ==[cd] %@) AND (relationships CONTAINS %@)";
NSString * fmt2 = @"relationships.@count != 0";
NSPredicate * p1 = [NSPredicate predicateWithFormat:fmt,str,mo];//expensive predicate
NSPredicate * p2 = [NSPredicate predicateWithFormat:fmt2,nil];//less expensive predicate
NSCompoundPredicate * cp = [NSCompoundPredicate andPredicateWithSubpredicates:@[p1,p2];
[self fetchSomethingWithPredicate:cp];
在上面的例子中,p1 和 p2 的顺序是否改变了复合谓词的计算方式?显然,首先评估 p2 会更有效,假设如果 p2 评估为 false,则 p1 将被忽略。
最佳答案
是的,评估的顺序很重要。始终将最有效和限制性的谓词放在左侧 - 尽快取消尽可能多的事物(尽管请记住,某些谓词确实非常昂贵)。
如果您中断调试器并打印出“cp”谓词,请确保它从左到右尽可能高效。
关于objective-c - NSCompoundPredicate 子谓词顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13484547/