Core Data Performance: NSPredicate comparing objects

匆匆过客 提交于 2019-12-22 04:17:21

问题


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?


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/8610687/core-data-performance-nspredicate-comparing-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!