Fetch Request Template (Part 2)Posted: July 21, 2012
I was looking into how to optimize queries in Core Data and wrote some code to test the various ways. It turned out that creating Fetch Request Templates was faster but I had no idea why and wrote a blog post about the results I got in various ways to do fetches in Core Data. I ended up asking about this in Stackoverflow and at first didn’t get much of an answer at first. The next day, I ended up realizing the biggest of the difference between a regular fetch and running on via a Fetch Request Template was that programmatically creating a fetch request it’s required that we provide a sort (versus a Fetch Request Template which doesn’t require the results to be sorted). I was going to update the code to test this assumption and just got around to it.
After a few days of that question on SO going unanswered, someone put a bounty on it and the question got enough attention to get it answered by more experienced iOS devs. I never realized how useful a bounty was.
So as you can see in the screen capture to the right, most of the difference between a regular fetch and a template fetch is due to the absence of a sort. Once I put a sort on the template fetch it was almost as slow as a regular sort – still a bit faster. I’m not sure what the insert/update costs of a index on the sort are but indexing both the search field and sort field doesn’t help all that much. There is still a bit of a difference between a regular fetch and a template search but nothing like the difference in putting an index on the search or sort field.
Again, here’s the code if you want to test other things: https://github.com/jinyk/CoreDataFetchTests.