The Optimal Way to Use List
public List<String> getNames(List<Human> humans) {
List<String> names = new ArrayList<>();
for(Human human : humans) {
names.add(human.name);
}
return names;
}
I bet you are understand what code will do. It’ll get names of every human on the list. Yeah, and so? according to Jake Wharton Slides and Android Perfomance pattern we can improve this code so it will be more perform. How ?
-
As you can see we need to copy from list humans to list string. So, size list of names and size list of users is same. and yes you can change it to be :
public List<String> getNames(List<Human> humans) { int humansSize = humans.size(); List<String> names = new ArrayList<>(humansSize); for(Human human : humans) { names.add(human.name); } return names; }
Why we need this ? do you know how list work. It will replicate itself by twice of current size if the list is full. Basically ArrayList is wrapper of array and as you know size of array is size of it is static and this is how ArrayList work why they are dynamic (make a new array and copy old data to new array). Default size of ArrayList in java is 12, and imagine how much time it will replicate if you have 1.000.000 data, 25 times. Thats why we need to define it size, so cost to do this operation is not 25 times longer.
-
According to video Android performance matter, the most efficient to do loop is by for index loop.
public List<String> getNames(List<Human> humans) { int humansSize = humans.size(); List<String> names = new ArrayList<String>(humansSize); for(int i = 0; i < humansSize; i++) { names.add(humans.get(i).name); } return names; }