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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With