I have a tableview, with a search bar. The table is loaded with 3700 text objects. The search occurs on the “title” text, which on average is 35 characters in length. I am looking for any optimization suggestions that would speed up the search sorting process. Currently, on average the search sort, is taking 0.733 seconds, which is about 95% of the entire search execution time. I am using a predicate that uses CONTAINS (has to, unfortunately) and then sortedArrayUsingComparator:, where I pass a block.
Thanks for taking a look!
Here is what I am doing:
//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];
}
EDIT
Per Catfish_Man’s suggestion below, I refactored the sort block to not instantiate objects inside the block unless absolutely necessary. I removed 4 object instantiations. The refactor brought with it, a +300% speed improvement:

Here is the refactored sort block:
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;
};
Biggest thing I see: you’re allocating 4 objects in your sort function. Object allocation just isn’t very fast! Instead, try using -rangeOfString:options: and passing NSCaseInsensitiveSearch.