2

I'm using core data of NSSqliteStoreType to store data in my iOS app. I need to store large amount of objects into database. To improve performance of Core data, I'm considering so many considerations like:

  1. Saving Batch wise
  2. Saving only after for loop ends
  3. Clearing Context to manage Memory

But it is taking so much time to save 100k objects. Please suggest me best practices to improve Performance of Core data while saving large amounts of data.

James Z
  • 12,209
  • 10
  • 24
  • 44
jagadeesh
  • 242
  • 2
  • 9

2 Answers2

3
  1. You should do the import on a non-UI thread with a context bound directly to the persistent store coordinator, not a child context of the main contex
  2. You should invoke [managedObjectContext save] once in every several hundreds of new objects inserted, depending on the object size and graph complexity. See this answer for details
  3. You should wrap your batch from step 2 in an @autoreleasepool block and reset the context after save before the autorelease block is exited. See this answer
Community
  • 1
  • 1
Leonid Usov
  • 1,508
  • 12
  • 16
  • Making it as a child vs. a separate context is not a major performance change. Using child contexts is less code and less chance to cause performance issues. It is generally the safer route. – Marcus S. Zarra Jul 30 '15 at 23:58
  • @MarcusS.Zarra oh yes it is. Making it a child context blocks main thread when you do `save` (well does a call on the main thread) and transfers data there. It means that to actually flush the data to the disk you will have to call `save` on the main context, which will run on the main thread. And then to reset it will mean that your app data will be unloaded from memory... In short, it does make difference. And it is not more code as well, just take the coordinator and set it as a context. – Leonid Usov Jul 31 '15 at 09:05
0

You should consider shipping your app with data pre-populated to avoid most of the overhead of the import. Assuming the data is static enough (most data is) you can pre-load all of the data up to the point of shipping the app and then when the app launches it only needs to grab data from the ship date forward (or last refresh date forward).

As Leonid Usov said, you should also do the import on a background context and save to disk in batches. That will help keep memory down and UI performance up. But at the end of the data, importing a lot of data is intensive and should be avoided by pre-loading as much as possible.

Marcus S. Zarra
  • 46,571
  • 9
  • 101
  • 182