How to Improve RecyclerView Performance in Android Using DiffUtil?
DiffUtil class is used to improve the performance of RecyclerView. The algorithm behind DiffUtil is that it takes two lists and finds differences between the two and provides the updated list as an output. It uses Eugene W. Myers’s difference algorithm to calculate the minimal number of updates. In this article, we will see its implementations. Note that we are going to implement this project using the Kotlin language.
Step by Step Implementation
Step 1: Create a new project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add view binding dependency
Go to build.gradle(app) and the following dependency inside the android tag and click sync now.
Step 3: Create a new model class
Create a new class Language.kt we will use data of custom generic “Language” to pass in the list that will be shown in RecyclerView.
Step 4: Create a new layout file and name it the single_item.xml file
Go to the single_item.xml file and refer to the following code. Below is the code for the single_item.xml file. It is the single item layout that we will use in RecyclerView.
Step 5: Working with the activity_main.xml
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. It has only a single RecyclerView which we will use to show our data.
Step 6: Create a new class and name it MyDiffUtil.kt
Go to MyDiffUtil.kt file and write the following code. Comments are added for a better understanding of the code.
Step 7: Working with the Adapter class
Create a new class RvAdapter.kt this will act as an Adapter class for the recycler view. Using View binding we use the generated class of the layout single_item.xml ie SingleItemBinding to add data and view in the recycler view of MainActivity.kt in our case. Comments are added before the code for better understanding.
Step 8: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.