Recyclerview first scroll slow/lags

from the CommonsWare Community archives

At July 18, 2019, 1:15pm, rd7773 asked:

RV shows max 3 items at a time (i.e. initially 2 but when scrolled 3rd item appears before 1st is completely out of viewport).

When the RV is scrolled for the first time, it lags due to view inflation in onCreateViewHolder(), which is called total of 6 times. After that its smooth.

How to solve for this ?

At July 18, 2019, 1:45pm, mmurphy replied:

onCreateView() is a method on Fragment. I would not expect you to have a fragment inside of a RecyclerView item.

But, in general, with fragments, to improve loading time, your primary option is to try to reduce the amount of work that you are doing in onCreateView() and onViewCreated(). The details of how to do that would depend a lot on what you are doing in those methods in the first place.

At July 18, 2019, 6:57pm, rd7773 replied:

I’m sorry i meant onCreateViewHolder(), i am using ConstraintLayout and data binding in xml.
View hierarchy is flat with 4-5 textviews and 2 buttons etc. With systrace i was able to find that the onCreateViewHolder is taking up most of the time in inflation (~700ms) which creates the jank in while scrolling first few items. But then when recycling happens, it works fine.

At July 18, 2019, 7:14pm, mmurphy replied:

700ms is a fairly long time. Usually, there is some form of I/O that is going on that consumes that amount of time. There will be a bit of I/O to read in the layout resource the first time, but that is usually fairly cheap due to the small size of the compiled edition of the resource.

So, I would start running experiments. For example, temporarily replace your layout resource’s contents with a single View, perhaps with a background color. See what your performance is like. If it is still bad, then the problem lies somewhere other than the actual layout inflation (e.g., data binding overhead). If it is better, slowly convert the layout to what you need it to look like, and see at what point your performance plummets.

Rather than systrace, you might consider Hugo or something similar to specifically measure the time you are spending in onCreateViewHolder().

At July 23, 2019, 9:30am, rd7773 replied:

Hugo seems to be similar in use case what Android Profiler already does i.e. give me java method traces.
Also, i can see that there is gc running whenever i scrolls the list which hints that process might be low on memory and it’s gc that is causing the jank.
Does android performs better on release build than debug ?

At July 23, 2019, 10:48am, mmurphy replied:

I am not aware of any significant performance differences.