Home » Android » Android: is it efficient to store references to Views as member variables?

Android: is it efficient to store references to Views as member variables?

Posted by: admin June 15, 2020 Leave a comment

Questions:

If I have a view that I will be referencing with decent regularity (to change its visibility, etc…), is it more efficient to store this View as a member variable or to execute findViewById() each time I need a reference to it?

The member variable requires memory usage, while the method my take more time. Is anyone aware of an established best practice for this?

How to&Answers:

It is much more efficient to store the reference. The memory cost of the reference will be minimal (I don’t remember the exact cost but it’s in the order of 4 bytes.)

Answer:

The real concern is where you store the reference. Above all else, you don’t want to be holding the reference when the View is no longer in use; Bad Things can result if you do.