I recently came across the concept of using Diffutil and SortedList.Callback<> to change data in instead of notifyDataSetChanged() directly but now I am confused which one to use at which condition.
1 Answers
According to the documentation for sortedList:
A Sorted list implementation that can keep items in order and also notify for changes in the list such that it can be bound to a RecyclerView.Adapter.
It keeps items ordered using the SortedList.Callback.compare(Object, Object) method and uses binary search to retrieve items. If the sorting criteria of your items may change, make sure you call appropriate methods while editing them to avoid data inconsistencies. You can control the order of items and change notifications via the SortedList.Callback parameter.
So, sortedList is a different implementation of List with more functionalities and capabilities. For example:
- Keeps last added items. When you update a common List with values that already exist in it tou will end up with duplicate values, while sortedList replaces items that are the same using the Callback's areItemsTheSame.
- Updates views smartly. When new items are added, onChange will only be called if one or more elements of the content changed.
- Better performance, If you are going to add multiple items to a SortedList, BatchedCallback call converts individual onInserted(index, 1) calls into one onInserted(index, N) if items are added into consecutive indices. This change can help RecyclerView resolve changes much more easily.
On the other hand, according to the documentation for diffUtil:
DiffUtil is a utility class that calculates the difference between two lists and outputs a list of update operations that converts the first list into the second one. It can be used to calculate updates for a RecyclerView Adapter.
So, diffUtil is a great tool that gives you the ability to compare two lists and find their differences. You can then use these comparison results to do whatever you want, but it doesn't do much more. On the above link you can find more about what's going on under the hood and its performance.
Conclusion:
- sortedList is a List with more functionalities, giving you more capabilities than a common List. But, also has different behavior in some cases than a common List.
- diffUtil is a great comparison tool for list contents. But, depending on the case it may not provide the best performance. Also, it needs to be used in background thread and the content of the lists it's comparing shouldn't change during the comparison process.
In both, read the documentation before using so as not to have unexpected results.

- 1,144
- 7
- 22