Differences between filtering Realm with NSPredicate and block

怎甘沉沦 提交于 2020-01-03 18:00:49

问题


I'm wondering about Realm's query performance. Given this code:

let result1 = realm.objects(Person.self).filter("age < 30 AND ... AND ...")
let result2 = realm.objects(Person.self).filter({ $0.age < 30 }).filter({$0.name .... }).filter({$0.nickname ...})

result1 is created by filtering Person objects using an NSPredicate, while result2 is filtering using the filter method from Swift's collection types.

Is there a performance difference between these two approaches to filtering?


回答1:


Yes, there is a performance difference between the two approaches.

The NSPredicate-based filtering is performed by Realm's query engine, which filters directly on the data in the Realm file without ever creating instances of Person. It can take advantage of knowledge of the database structure to perform the queries more efficiently (by using indexes, for instance). In contrast, the block based filtering must create instances of Person for each object in your Realm in order to pass them to the block.

There are other semantic differences as well, which primarily stem from the differing result types of the two methods. The NSPredicate-based filtering returns a Results<T> rather than the [T] that the block-based filtering returns.

Results<T> is a live-updating view onto the results of your query. You can hand one to a view controller and its contents will update after other parts of your application perform writes that cause new objects to begin matching the predicate. You can also register for change notifications to learn about when new objects begin matching the predicate, an existing object stops matching it, or when an object that matches was modified in some way.



来源:https://stackoverflow.com/questions/43271459/differences-between-filtering-realm-with-nspredicate-and-block

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