Differences between filter scopes with NSPredicate and block
I am wondering about query performance in Realm. 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 objects Person
using NSPredicate
, and result2
- using a method filter
from Swift collection types.
Is there a performance difference between the two filtering approaches?
source to share
Yes, there is a performance difference between the two approaches.
Based filtering NSPredicate
is performed by the Realm Query Engine, which filters the data in the Realm file directly without instantiating it Person
. It can use knowledge of the database structure to perform queries more efficiently (for example, using indexes). In contrast, block filtering has to instantiate Person
every object in your Realm in order to pass them into a block.
There are other semantic differences, which are mainly related to the different types of results of the two methods. The filtering NSPredicate
returns Results<T>
, not [T]
that block-based filtering returns.
Results<T>
is a real-time view of the results of your query. You can pass it to a view controller, and its content will be updated after other parts of your application make records that cause new objects to start matching the predicate. You can also register for change notifications to see when new objects match a predicate, an existing object will no longer match, or when the corresponding object has been modified in some way.
source to share