Search code examples
androidmemoryandroid-viewlocal-variablesmember-variables

difference between view reference to member variable and local variable


suppose I have an activity, and it contains a TextView. I can initialize the TextView either to a member variable or to a local variable. is there any memory wise difference between these to initialization ?

example : Activity with local view reference:

 public class MainActivity extends Activity{

    @OVerride
    public void onCreate(Bundle b){
       TextView textView = (TextView)findViewById(R.id.my_text_view_id);
    }
}

Activity with member view reference:

 public class MainActivity extends Activity{
    TextView mTextView;

    @OVerride
    public void onCreate(Bundle b){
       mTextView = (TextView)findViewById(R.id.my_text_view_id);
    }
}

Solution

  • You should always use the minimal scope. So when you declare a variable you should ask yourself:

    "Will I need this variable later in a different function?"

    Yes -> Use a member variable

    No -> Use a local variable

    Edit:

    What also to consider is the cost of object creation:

    If a function does get called repeatedly it is a good practice to instanatiate an object only once, store it as a member variable and reuse it instead of creating a new instance every time the function gets called.

    So the 2nd important question is:

    "Will this function get called a lot and do I really need a new instance of the object stored in the variable?"

    Yes, often, and no, I can reuse the same object over -> use a member variable. This way the same memory is used and no garbage gets piled up. Use only for large Arrays or objects, it is not needed for simple int vars in loops.