When I have a list with a bigger amount of elements (around 7000) and I add sorting to the query, change listeners are getting very slow. This is not the case when only one field is given. From the second field it slows down a lot. It also seems to depend on what field type is given to sorting. Booleans seem to be quite fast. Dates are also slower when only one is used.
Let me show you what I do: very simple query on all objects with multiple sorting elements:
val theList = realm.where(TheObject::class.java)
.sort(
arrayOf("fieldBool", "fieldDate", "fieldString"),
arrayOf(Sort.DESCENDING, Sort.DESCENDING, Sort.DESCENDING)
)
.findAllAsync()
theList.addChangeListener { result: RealmResults<TheObject> ->
// Set the list to the view.
}
Now, when some object in this resulting list is changed, the change listener needs a lot of time to update the data. Also other change listeners on the same looper are very slow.
even if I sort the result after adding a changeListener (in the change lsitener):
val theList = realm.where(TheObject::class.java)
.findAllAsync()
theList.addChangeListener { result: RealmResults<TheObject> ->
viewToSet.list = result.sort(
arrayOf("fieldBool", "fieldDate", "fieldString"),
arrayOf(Sort.DESCENDING, Sort.DESCENDING, Sort.DESCENDING)
)
}
the update happens very slow. I found out that it might has to do with listening to do with calculating the changeset. If I add a changelistener to the realm instead of the result, it works quite fast. Still what is interesting is that I do not add a changeListener to the sorted list but to the unsorted list. sorting then works quite fast inside of the listener, but as soon as I have a sorted RealmResults living somewhere, the changeset creation seems to take a while...
Is this a bug or just a weakness of Realm?
The problem is a comination of two Edgecases/Bugs in realm:
RealmResult
will be taken into account when creating changesets, even when the RealmResult
itself has no listener (see https://github.com/realm/realm-java/issues/6614).ObjectA -> ObjectB -> RealmList<ObjectA>
) is fetched in a list and that list gets sorted, the changeset creation takes a long time.I fixed this by removing the cycling reference. Now it works.