ma11hew28
ma11hew28

Reputation: 126457

Core Data Performance: NSPredicate comparing objects

If my Author NSManagedObject model has a authorID attribute (determined by the server), will an NSFetchRequest perform better if the NSPredicate filters by authorID rather than the complete Author object? Let's say I'm fetching all Book NSManagedObjects by a certain author. Which predicateFormat is better?

[NSPredicate predicateWithFormat:@"author = %@", anAuthor]

or

[NSPredicate predicateWithFormat:@"author.authorID = %@", anAuthor.authorID]

What's the best way to profile this? I have Core Data testing working with OCUnit (SenTestingKit). Does iOS have something like Ruby's Benchmark module?

Upvotes: 8

Views: 4167

Answers (2)

Daniel Eggert
Daniel Eggert

Reputation: 6715

The first one (using just Author) would probably be faster, but only testing will tell you for sure.

If you fetch (e.g. Book) objects that have an relationship to Author and you use a predicate

[NSPredicate predicateWithFormat:@"author = %@", anAuthor]

SQLite can see if the merge table from Book to Author has the right primary key for that given author. In other words, the predicate turns into a check for the Author entities primary key. CoreData still has to consult the merge table, though.

If you use

[NSPredicate predicateWithFormat:@"author.authorID = %@", anAuthor.authorID]

then SQLite will have to join the merge table with the actual Author table and then match the resulting authorID column. That would be more work. And it would break down if authorID isn't indexed.

Upvotes: 0

paulbailey
paulbailey

Reputation: 5346

It might be worth running your app with an argument of -com.apple.CoreData.SQLDebug 1, as detailed here.

You could then see if Core Data was executing the same SQL in both circumstances (assuming you're using a SQLite store).

Upvotes: 1

Related Questions