Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findViewById vs local reference in Activity

Would it be there noticeable speed improvement if I would create local references to needed view elements (e.g. EditText or Button) in my activity (in onCreate()) and use them for accessing needed elements or it does not much matter if I always use findViewById() when I need to access some particular element?

like image 323
Laimoncijus Avatar asked Jun 17 '10 18:06

Laimoncijus


3 Answers

It's an old question, but let me post my answer for anyone who happen to be curious just as me: at least in api level 17 (4.2.2), DFS (Depth First Search) is used to look for a view, and no caching mechanism exists (meaning search will be repeated every time you call findViewById()).

like image 108
kar Avatar answered Oct 22 '22 13:10

kar


It will be a speed improvement if you have a complex layout and you are accessing those Views too often. It is a good practice to define private variables and to bind them to the references returned by findViewById once in onCreate() then accessing them throughout your code.

If you are accessing those Views just once for, let's say, adding OnClickListeners to them, I don't think it is needed to create local references, as you call them.

like image 32
licorna Avatar answered Oct 22 '22 12:10

licorna


If you are using a ListActivity this is what the View Holder pattern advocates. I would say it depends on how often the view is getting refreshed.

Here's a video and pdf from Google I/O which talks about implementing a ViewHolder pattern in the getView method of a ListAdapter

The world of ListView

like image 2
mmaitlen Avatar answered Oct 22 '22 14:10

mmaitlen