Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
}
like image 606
droidev Avatar asked Dec 06 '25 23:12

droidev


2 Answers

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.

like image 91
Björn Kechel Avatar answered Dec 09 '25 13:12

Björn Kechel


Memory wise global variables are much more prone to memory leaks. The scope any variable depends on its scope. For local variable, the scope is closing braces of the respected method, and variable is automatically garbage collected after the execution of closing braces. Where as global variable will reside in memory until the any object of that class is in memory.

like image 27
MrWaqasAhmed Avatar answered Dec 09 '25 13:12

MrWaqasAhmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!