So, I am trying to fetch around 2000 objects from core-data and trying to find out which would be the fastest way to fetch them.
Without NSPredicates:
When I add this block (below), the if statement takes 90% of the total time taken to execute, which is understandable, and so I comment it out.
Block {
NSError *error;
NSManagedObjectContext *context = <#Get the context#>;
// The IF block
/* if (![context save:&error])
{
NSLog(@"error %@", error);
}
*/
// The block above takes 90% of the total time of fetch
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *theEntity = [NSEntityDescription
entityForName:@"EntityName" inManagedObjectContext:context];
[fetchRequest setEntity:theEntity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
}
With NSPredicates:
I set the predicate as
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"handle == %@",handle];
and perform the same fetch as shown in Block()
It can be seen that the overall time is the exact opposite -it’s around 90% faster if I use the IF BLOCK ~ 6 seconds.
Otherwise, if that block is commented, the fetching time is a LOT ~ 3 minutes. This happens only when set a predicate for the fetchRequest.
Can someone please explain ?
That is,
/*
Save + straight fetch = slow, due to saving.
Straight fetch - pretty fast.
Predicate fetch, slow.
Save + predicate fetch, much faster?
*/
(Guesswork, hopefully educated) After a save the context can perform a predicated fetch directly against the database as it knows that there are no objects whose changes have not been written to the DB yet. Without the save, it has to fetch against the DB and also any extant objects who may have unsaved changes.