YoungCoconutCode YoungCoconutCode - 2 years ago 134
Java Question

Android lists (ArrayList, List, etc.): addAll() vs redefining reference

If I have something like:

ArrayList<Data> mList = new ArrayList();


public void setList(ArrayList<Data> list) {
mList = list;

public void updateList(ArrayList<Data> list) {

Which is more efficient,
and why? What is the best practice?


Not to be confused with this question.

Answer Source

There is an enormous conceptional difference between the two.

Your setList() takes a reference to a list; and changes your mList ... to point to that reference.

Whereas your updateList() copies all the references from the incoming list into your existing mList object.

Meaning: setList() does require less CPU operations compared to updateList() ... but the key thing is: now mList can be changed from outside of your class. Like in:

List someList = ...

will clear "your" mList as well; but

List someList = ...

will not affect your "mList".

That's the main difference you should be aware of.

Performance is actually not the real issue to be concerned about here!

In general: do not worry too much about performance. Because: you will not get it right anyway. For example, there is the JIT compiler turning naive assumptions upside down.

Long story short: focus on semantics of operations; don't restrict yourself to "performance" aspects.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download