I often define variables as class/instance variables ('global' before edit, thanks for the clarification) in my class while programming in Android. In case I need to access it later, say in another method after it's been assigned in onCreate()
.
For the occasions where I don't actually access them later, Android Studio's Lint code inspection throws warnings stating that the "Field can be converted to a local variable".
I know I will get the same functionality either way, but is there any performance or security benefit to inline/local method variables in Java (specifically on Android, but also in general) vs. declaring them as private class/instance variables within a class?
EDIT/CLARIFICATION: By 'global', I meant in the scope of the class. (What I know understand to be referred to as 'class' or 'instance' variables, my bad) Accessible by all methods within the class and not an inline or method specific variable. Maybe a sort of example code will illustrate my point. EX:
public class MyActivity {
//Android Studio Lint will throw Java Class structure 'Field can be local' warnings
//which is why I'm referring to these variables as "global"
private SomeDataType myPrivateVariable1; //'Field can be converted to a local variable'
public SomeDataType myPublicVariable1; //'Field can be converted to a local variable'
private SomeDataType myPrivateVariable2;
public SomeDataType myPublicVariable2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity_layout);
//assign data to variables from either intent bundle or preferences or w/e
myPrivateVariable1 = SOME_DATA;
myPublicVariable1 = SOME_DATA;
//AS will suggest change to:
// SomeDataType myPrivateVariable1 = SOME_DATA;
// SomeDataType myPublicVariable1 = SOME_DATA;
myPrivateVariable2 = SOME_DATA;
myPublicVariable2 = SOME_DATA;
//AS Lint will throw warning that variables can be converted b/c only used here
someMethod(myPrivateVariable1);
someOtherMethod(myPublicVariable1);
//run a method that uses the variables
myMethodUsingVariable2(input);
}
private void myMethodUsingVariable2(DataType input) {
//access the variables in multiple methods will not trigger the warning
if (input == something) {
//do something with 'myPrivateVariable2' and 'myPublicVariable2'
}
}
}
What is the performance benefit to this? If later I find I need to use either myPrivateVariable1
or myPublicVariable1
in another method as I add a feature or change something, it would be easier to write new methods that used the data if they were already saved to a defined class variable and assigned a value from the onCreate()
method. Is the only benefit memory allocation that will only significantly affect performance if the variables are large data sets? What would be the difference between public and private in that regards as well?