提高大型数据集上谓词的性能

时间:2014-01-14 12:57:18

标签: ios objective-c nspredicate

我有30907项的大数据。目前,我正在使用NSPredicate进行过滤。 但它很慢。因此,我正在寻找一种更快的方式来处理它们。

这是我目前过滤30907项的代码:

predicate = [NSPredicate predicateWithFormat:
                 @"((full beginswith[cd] %@) OR (full == [cd] %@) OR (search ==[cd] %@)) OR (search CONTAINS[cd] %@) OR (search beginswith[cd] %@)",matchString,matchString,matchString,strNoSpace,strNoSpace];

NSArray * arrResult = [arrSongs filteredArrayUsingPredicate:predicate];

结果是正确的,但速度很慢。

3 个答案:

答案 0 :(得分:1)

使用谓词的更好方法是......条件,它将限制大多数数据应该按顺序排在第一位。它将使您的predicate快速工作,因为下一个条件将评估较少的数据。

修改

这不仅取决于谓词,还与您使用的数据结构有关。每个数据结构也都有搜索成本,例如在array中搜索比set慢。虽然array上的迭代速度比set快。根据要求,我们应该使用数据结构。

答案 1 :(得分:0)

也许您可以尝试删除(full == [cd] %@),此条件已经完整评估beginswith[cd]。换句话说,(full == [cd] %@)的字符串是beginswith[cd]的一个子集。

同样的事情发生在(search beginswith[cd] %@)上,它是(search CONTAINS[cd] %@)的一个子集。

所以,试试这个:

[NSPredicate predicateWithFormat:
                 @"((full beginswith[cd] %@) OR (search ==[cd] %@)) OR (search CONTAINS[cd] %@)",matchString,matchString,strNoSpace];

答案 2 :(得分:0)

您可以简化条件表达式:

看看它:

((以[cd] matchString开头)或者(完全== [cd] matchString)或者(搜索== [cd] matchString))或者(搜索CONTAINS [cd] strNoSpace)或者(搜索以[cd] strNoSpace开头) )

首先,所有术语都与OR相关联。你在括号中不需要括号:

(以[cd] matchString开头)或(完全== [cd] matchString)或(搜索== [cd] matchString)或(搜索CONTAINS [cd] strNoSpace)或(搜索以[cd] strNoSpace开头)< / p>

第二:如果字符串与存储的值匹配,则以它开头。所以你不需要检查==

(以[cd] matchString开头)或(搜索CONTAINS [cd] strNoSpace)或(搜索以[cd] strNoSpace开头)

第三:如果一个字符串以字符串开头,则它包含字符串:(如果你有大量的点击,这个可能会使性能变差。请查看它。)

(以[cd] matchString开头)或(搜索CONTAINS [cd] strNoSpace)