-
Enhancement
-
Resolution: Unresolved
-
P4
-
8, 9
-
generic
-
generic
This issue appeared while profiling JavaFX on embedded platforms, where we were noticing a lot of temporary object overhead. One surprising place was in the creation of temp arrays due to Collections.sort when the source list had a single element (I guess we have a lot of those...).
This is the logic in Collections.java:
public static <T extends Comparable<? super T>> void sort(List<T> list) {
Object[] a = list.toArray();
Arrays.sort(a);
ListIterator<T> i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set((T)a[j]);
}
}
It would be relatively trivial to change:
public static <T extends Comparable<? super T>> void sort(List<T> list) {
if (!list.isEmpty() && list.size() > 1) {
Object[] a = list.toArray();
Arrays.sort(a);
ListIterator<T> i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set((T)a[j]);
}
}
}
One problem here is that computing "size" on some lists can be quite expensive, so you might need some package API to do a quick check on known list types (such as ArrayList) but in the general case if not isEmpty() then you have to fall through. Also you probably want to have special cases for when you are sorting a 2 element list.
This is the logic in Collections.java:
public static <T extends Comparable<? super T>> void sort(List<T> list) {
Object[] a = list.toArray();
Arrays.sort(a);
ListIterator<T> i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set((T)a[j]);
}
}
It would be relatively trivial to change:
public static <T extends Comparable<? super T>> void sort(List<T> list) {
if (!list.isEmpty() && list.size() > 1) {
Object[] a = list.toArray();
Arrays.sort(a);
ListIterator<T> i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set((T)a[j]);
}
}
}
One problem here is that computing "size" on some lists can be quite expensive, so you might need some package API to do a quick check on known list types (such as ArrayList) but in the general case if not isEmpty() then you have to fall through. Also you probably want to have special cases for when you are sorting a 2 element list.
- duplicates
-
JDK-8021981 RFE: Optimize j.u.Collections
-
- Closed
-
- relates to
-
JDK-7065380 (coll) Collections.sort(List<T>) should support Collections.singletonList(T)
-
- Open
-