To keep this question simple, consider a scenario where I am creating an Android Activity that simply reads data from an external source and uses that data within a TextView. I am seeing dramatic performance differences with the following two scenarios:
- Reading the external data and populating the Activity's instance variables to use throughout the Activity. Results in execution time of 2220.479170 ms and the DalvikVM frees memory 12 times.
- Reading the external data into local variables each time it needs to be used within class methods. Results in 1150.434916 ms and the DalvikVM frees memory 6 times.
As you can see, using instance variables takes more than 1070 milliseconds longer to execute than using local variables and there are double the amount of memory leaks. The reason why I switched from using local to instance variables is because I was using the same data in different methods, therefore using an instance variable makes more sense than using multiple local variables.
My question is why is the performance much more efficient when using local variables rather than instance variables and why does memory need to be freed double the amount of times?
A code snippet:
public class DataActivity extends Activity {
//Raw value table entries
//Table 61
private int nbr_chns_set1;
private int nbr_blks_set1;
private int nbr_blk_ints_set1;
private int max_int_time_set1;
//Table 62
private int blk_end_read_flag;
private int blk_end_pulse_flag;
//Table 63
private int last_block_element;
private int nbr_valid_int;
private int nbr_valid_blocks;
private int interval_order;
//Table 64
ArrayList<String> table64Entries;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lp_data);
initializeVariables();
classMethods();
}
public void initializeVariables() {
//Populate class variables from values in Table 61
TableReader tableReader = new TableReader(this, R.raw.table61);
ArrayList<String> table61Entries = tableReader.readTable();
nbr_chns_set1 = table61Entries.get(98);
nbr_blks_set1 = table61Entries.get(90);
nbr_blk_ints_set1 = table61Entries.get(94);
max_int_time_set1 = table61Entries.get(102);
blk_end_read_flag = table61Entries.get(22);
blk_end_pulse_flag = table61Entries.get(26);
//Populate class variables from values in Table 63
tableReader = new TableReader(this, R.raw.table63);
ArrayList<String> table63Entries = tableReader.readTable();
last_block_element = table63Entries.get(38);
nbr_valid_int = table63Entries.get(5));
nbr_valid_blocks = table63Entries.get(34);
interval_order = table63Entries.get(22);
//Populate class variables from values in Table 64
tableReader = new TableReader(this, R.raw.table64);
table64Entries = tableReader.readTable();
}
public void classMethods() {
...
}