Rocky Rocky - 4 years ago 115
Swift Question

How efficient is Realm at filtering/sorting within a to-one relationship?

Suppose I wanted to fetch the person who most recently adopted a specific dog (contrived example). Right now I'm doing something like this:

let realm = try! Realm()
let predicate = NSPredicate(format: "dog.dogId = %@", dogId)
return realm.objects(Person.self).filter(predicate).sorted(byKeyPath: "dog.adoptionDate", ascending: false).first


My question is how efficient is this? Is it similar to doing a
JOIN
in a typical relational database? If I wanted to make things faster, would it be a good idea to store dogId and adoptionDate on the person object — or is that unnecessary?

Answer Source

There is some overhead from sorting over a link, but it is very unlikely to be significant unless your objects happen to already be in sorted order, as then the sort itself would take negligible time.

Realm links generally perform significantly better than relational joins (the row number of the target is stored directly, rather than having to perform an index lookup (or a table scan if you haven't indexed the relevant columns)), at the cost of being less flexible.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download