DiffUtil vs. notifyDataSetChanged()

In this shot, you will learn a better and more efficient way to handle resources while implementing a recycler view in Android.

Developing software is all about efficiency.

A RecyclerView is an advanced, flexible version of a ListView. One of the reasons for this is that RecyclerView has a more extensible framework, especially since it provides the ability to implement both horizontal and vertical layouts. Use the RecyclerView widget when you have data collections whose elements change at runtime based on user action or network events.

Problem

Situations may arise when our recycler view will want to notify registered observers that the data set has changed. This could mean refreshing a page or adding new elements.

To tell the Recycler View that an item in the list has changed, we call notifyDataSetChanged(). However, this has a few drawbacks:

  • It redraws every view again - The Recycler view has no idea of changes on the list, thus it assumes that all items are invalid and recreates the views again.
  • Very expensive - Since it requires new instances and resources each time, it’s a very expensive method.

Solution

But there’s always a better solution!

According to the official Android Documentation:

  • DiffUtil is a utility class that can calculate the difference between two lists and output a list of update operations that converts the first list into the second one.

  • It’s also a helper for Recycler view adapters that calculate changes in lists and minimize modifications.

Benefits

  • Only redraws changed items
  • Animates by default
  • Much More Efficient

I do hope you’ve grasped the difference between both methods and how to adapt to a more efficient approach.

I will be publishing another article on implementing DiffUtil on your Android application!

Stay Tuned!