13

Is it crucial for performance to have ViewHolder as static in a ViewHolder pattern?

A ViewHolder object stores each of the component views inside the tag field of the Layout, so you can immediately access them without the need to look them up repeatedly. First, you need to create a class to hold your exact set of views. For example:

static class ViewHolder {
  TextView text;
  TextView timestamp;
  ImageView icon;
  ProgressBar progress;
  int position;
}
Eugene
  • 59,186
  • 91
  • 226
  • 333

3 Answers3

8

It's not crucial for performance, it is about using. If ViewHolder class will not be static - you have to provide instance of parent class:

No enclosing instance of type Type is accessible. 
Must qualify the allocation with an enclosing instance of type Type 
(e.g. x.new A() where x is an instance of Type).
Jin35
  • 8,602
  • 3
  • 32
  • 52
  • 10
    What if the ViewHolder class is used inside the adapter class itself? Then you do not have to provide an instance of parent class... – IgorGanapolsky Mar 03 '14 at 20:47
  • But that may leak the adapter as pointed in http://stackoverflow.com/questions/10864853/when-exactly-is-it-leak-safe-to-use-anonymous-inner-classes – divyenduz Oct 17 '15 at 06:56
1

Edit: misunderstood the question -- it seems you are asking specifically about making it static. That shouldn't be crucial for performance, but the idea is every bit helps.

Final edit here: Static nested class in Java, why?

====

Orig answer below:

It's very nice to squeeze performance out of a heavy ListView (or some other type of recycled AdapterView). However the best way to tell would be to profile the performance somehow.

Also at Google IO 2010 they recommend this method:

http://www.youtube.com/watch?v=wDBM6wVEO70

Edit:

Also here's a link to traceview to profile the performance, though I'm unsure how well it works.

http://developer.android.com/tools/debugging/debugging-tracing.html

Community
  • 1
  • 1
pjco
  • 3,826
  • 25
  • 25
-3

It's not mandatory to do that. But when you use to do like this, you are using the views again when your adapter view is null. You are creating a view and assigning values to the view part, and tag the whole view using static class ViewHolder. So when you come back and view is not null, then visible part will come from to get the tag. This is how you will create less object as well less work load on adapter.

IgorGanapolsky
  • 26,189
  • 23
  • 116
  • 147
PiyushMishra
  • 5,743
  • 6
  • 37
  • 57