2 Different ways of doing the same thing (i.e Fetching messages from Database)
Calling Class:
ArrayList<String> messages = new ArrayList<String>();
messages = Db.getAllMessage(messages);
Database Class:
public ArrayList<String> getAllMessage(ArrayList<String> m) {
m= /* get messages from DB */
return m;
}
Calling Class:
ArrayList<String> messages = new ArrayList<String>();
messages = Db.getAllMessage();
Database Class:
public ArrayList<String> getAllMessage() {
ArrayList<String> temp = new ArrayList<String>();
temp = /* get messages from DB */
return temp;
}
My Question is, in Scenario 2,
In the talk video Android Application Architecture (Android Dev Summit 2015), Adam Powell mentions that GC is your enemy and suggests to use Scenario 1 in case of Android app.
The variable itself will go out of scope and be deallocated (as the call stack shrinks).
The object that the variable points to (the ArrayList) still has another reference pointing to it, so it will not be collected.
It will go away when no more references (such as your messages variable or field) exists.
This is not a memory leak.
In both scenarios, it is pointless to create the empty ArrayList before calling the function (and you should be asking yourself what happens to it once you receive the new one, just like you worried about temp. Don't worry, it's only pointless, not dangerous or "leaky").
Do this instead:
ArrayList<String> messages = Db.getAllMessages();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With