DiffUtil 和 SortedList 哪个更高效?

Which is more efficient DiffUtil or SortedList?

我最近遇到了使用 DiffutilSortedList.Callback<> 来更改数据而不是 notifyDataSetChanged() 直接但现在我很困惑在什么情况下使用哪个。

根据 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.

因此,sortedList 是 List 的不同实现,具有更多的功能和能力。例如:

  • 保留最后添加的项目。当您使用其中已存在的值更新公共列表时,您最终会得到重复的值,而排序列表会使用回调的 areItemsTheSame 替换相同的项目。
  • 智能更新视图。添加新项目时,仅当内容的一个或多个元素发生变化时才会调用 onChange。
  • 更好的性能,如果您要将多个项目添加到 SortedList,BatchedCallback 调用会将单个 onInserted(index, 1) 调用转换为一个 onInserted(index, N),如果项目被添加到连续的索引中。此更改可以帮助 RecyclerView 更轻松地解决更改。

另一方面,根据 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.

因此,diffUtil 是一个很棒的工具,让您能够比较两个列表并找到它们的差异。然后你可以使用这些比较结果来做任何你想做的事,但它并没有做更多的事情。在上面 link 您可以找到更多关于引擎盖下发生的事情及其性能的信息。

结论:

  • sortedList是一个功能更多的List,比普通的List给你更多的能力。但是,在某些情况下也有与普通列表不同的行为。
  • diffUtil 是一个很好的列表内容比较工具。但是,根据具体情况,它可能无法提供最佳性能。另外,它需要在后台线程中使用,并且它所比较的​​列表的内容在比较过程中不应该改变。

两者都请在使用前阅读文档,以免出现意想不到的结果。