Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad performance of Core Data "save" operation on the managedObjectContext

I have an iPhone/iPad app which uses Core Data.

In my DB I have only one table, though it's a very large one (about 40 columns). When i build the DB i create and insert about 13,000 new entities, and then I call 'saveContext'.

for (NSArray *singleDiamond in allDiamonds)
{
     @try 
     {
         if (//Some validation)
         {
             Diamond *diamond = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Diamond class]) 
                                                              inManagedObjectContext:self.managedObjectContext];
             //Do setup for diamond...
         }
     }
     @catch (NSException *exception) {NSLog(@"%@",[exception message]);}
 }
NSLog(@"Start Saving Context...");
[self saveContext];
NSLog(@"End Saving Context...");

My problem id that only the 'saveContext' method, takes 23 seconds to execute. That's not acceptable.

Is there something I do wrong? How can I improve the performance here?

like image 973
Avi Shukron Avatar asked Feb 23 '23 09:02

Avi Shukron


1 Answers

You should call saveContext several times during the batch insert, and then call reset to "forget" the previous inserted managed objects. For example in my case I save the context every 100 objects. Moreover you should create a dedicated context for the import and optimize it (by setting the undomanager to nil, since you don't need to roolback/undo the whole insert). Read here: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdImporting.html

like image 156
daveoncode Avatar answered Feb 24 '23 23:02

daveoncode