Search code examples
ioscore-datansfetchrequest

Core Data fetching is slow


I am retrieving a series of objects from a large database. There are between 1-20 results for each lookup. Using a fetch request as following:

NSPredicate *indexPredicate = [NSPredicate predicateWithFormat:
                          @"index == %@",indexNumber];

I can get results back in a relatively short period of time.

CoreData: annotation: total fetch execution time: 0.0623s for 9 rows.

However when merging all predicates with [NSCompoundPredicate orPredicateWithSubpredicates: to do the fetch in one operation the speed drops.

CoreData: annotation: total fetch execution time: 0.3890s for 195 rows.

I have tried indexing,setting fetch and batch limits, but am unable to reduce the total fetch time. I have also tried to execute the fetch requests at the same time one by one using GDC but am having trouble setting it up. How can I reduce the time to fetch this data?


Solution

  • Combining 20 index lookups with OR is a lot of comparison in the fetch. You can improve matters by collecting the index values into an array and then using a single comparison with IN. Something like

    NSArray *indexesToFetch = // A bunch of NSNumbers with index numbers of interest
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"indexNumber in %@", indexesToFetch];
    

    If you have a lot of data to search through, this is still a lot of work. But using IN for something like this will generally be much faster than using a whole bunch of ORs.