public class DiffUtil extends Object
It can be used to calculate updates for a RecyclerView Adapter.
DiffUtil uses Eugene W. Myers's difference algorithm to calculate the minimal number of updates to convert one list into another. Myers's algorithm does not handle items that are moved so DiffUtil runs a second pass on the result to detect items that were moved.
If the lists are large, this operation may take significant time so you are advised to run this
on a background thread, get the DiffUtil.DiffResult
then apply it on the RecyclerView on the main
thread.
This algorithm is optimized for space and uses O(N) space to find the minimal number of addition and removal operations between the two lists. It has O(N + D^2) expected time performance where D is the length of the edit script.
If move detection is enabled, it takes an additional O(N^2) time where N is the total number of added and removed items. If your lists are already sorted by the same constraint (e.g. a created timestamp for a list of posts), you can disable move detection to improve performance.
The actual runtime of the algorithm significantly depends on the number of changes in the list and the cost of your comparison methods. Below are some average run times for reference: (The test list is composed of random UUID Strings and the tests are run on Nexus 5X with M)
Due to implementation constraints, the max size of the list can be 2^26.
Modifier and Type | Class and Description |
---|---|
static class |
DiffUtil.Callback
A Callback class used by DiffUtil while calculating the diff between two lists.
|
static class |
DiffUtil.DiffResult
This class holds the information about the result of a
calculateDiff(Callback, boolean) call. |
Modifier and Type | Method and Description |
---|---|
static DiffUtil.DiffResult |
calculateDiff(DiffUtil.Callback cb)
Calculates the list of update operations that can covert one list into the other one.
|
static DiffUtil.DiffResult |
calculateDiff(DiffUtil.Callback cb,
boolean detectMoves)
Calculates the list of update operations that can covert one list into the other one.
|
public static DiffUtil.DiffResult calculateDiff(DiffUtil.Callback cb)
cb
- The callback that acts as a gateway to the backing list datapublic static DiffUtil.DiffResult calculateDiff(DiffUtil.Callback cb, boolean detectMoves)
If your old and new lists are sorted by the same constraint and items never move (swap
positions), you can disable move detection which takes O(N^2)
time where
N is the number of added, moved, removed items.
cb
- The callback that acts as a gateway to the backing list datadetectMoves
- True if DiffUtil should try to detect moved items, false otherwise.