我有一个带有搜索栏的tableview。该表加载了3700个文本对象。搜索发生在“标题”文本上,平均长度为35个字符。我正在寻找任何可以加快搜索排序过程的优化建议。目前,搜索排序平均为0.733秒,约为整个搜索执行时间的95%。我正在使用一个使用CONTAINS的谓词(不幸的是必须),然后使用sortedArrayUsingComparator:,我传递一个块。
谢谢你看看!
这是我正在做的事情:
//My sorting block implementation
self.mySortBlock = ^NSComparisonResult(id obj1, id obj2) {
Tip *tip1 = obj1;
Tip *tip2 = obj2;
NSString *string1 = [tip1.subject lowercaseString];
NSString *string2 = [tip2.subject lowercaseString];
NSUInteger searchStringLocation1 = [string1 rangeOfString:[self.userSearchText lowercaseString]].location;
NSUInteger searchStringLocation2 = [string2 rangeOfString:[self.userSearchText lowercaseString]].location;
if (searchStringLocation1 > searchStringLocation2) return NSOrderedDescending;
if (searchStringLocation1 < searchStringLocation2) return NSOrderedAscending;
return NSOrderedSame;
};
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *filter = [NSPredicate predicateWithFormat:@"subject CONTAINS [cd] %@", searchText];
NSArray *filtered = [myArray filteredArrayUsingPredicate: filter];
self.sorted = nil;
self.sorted = [filtered sortedArrayUsingComparator:self.mySortBlock];
}
修改 根据Catfish_Man的建议,我重构了排序块,除非绝对必要,否则不会在块内实例化对象。我删除了4个对象实例。重构带来了它,速度提高了300%:
这是重构的排序块:
self.mySortBlock = ^NSComparisonResult(id obj1, id obj2) {
NSUInteger searchStringLocation1 = [[obj1 subject] rangeOfString:self.userSearchText options:NSCaseInsensitiveSearch].location;
NSUInteger searchStringLocation2 = [[obj2 subject] rangeOfString:self.userSearchText options:NSCaseInsensitiveSearch].location;
if (searchStringLocation1 > searchStringLocation2) return NSOrderedDescending;
if (searchStringLocation1 < searchStringLocation2) return NSOrderedAscending;
return NSOrderedSame;
};
答案 0 :(得分:3)
我看到最大的事情:你在sort函数中分配了4个对象。对象分配不是很快!相反,尝试使用-rangeOfString:options:并传递NSCaseInsensitiveSearch。