-
Enhancement
-
Resolution: Fixed
-
P4
-
8, 9
-
b117
-
Verified
Currently Arrays.asList() (Arrays.ArrayList) class inherits the iterator() method from AbstractList which is not specialized enough, performs unnecessary bookkeeping like modCount tracking and holds a reference to the Arrays.ArrayList object which currently makes Arrays.ArrayList object heap allocation unavoidable even if it's short-lived and used for single iteration. For example, consider the following code:
public int sumArray() {
return sum(Arrays.asList(arr));
}
public static int sum(Iterable<Integer> data) {
int sum = 0;
for (int item : data) sum+=item;
return sum;
}
Here allocation of Arrays.ArrayList object is not optimized by JIT, so every call creates a heap object.
Optimized implementation of Arrays.iterator() is possible which returns custom iterator object. It should work faster and don't allocate anything in the test above.
public int sumArray() {
return sum(Arrays.asList(arr));
}
public static int sum(Iterable<Integer> data) {
int sum = 0;
for (int item : data) sum+=item;
return sum;
}
Here allocation of Arrays.ArrayList object is not optimized by JIT, so every call creates a heap object.
Optimized implementation of Arrays.iterator() is possible which returns custom iterator object. It should work faster and don't allocate anything in the test above.