Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8015708

Collections.sort creates a temporary array even for elements of size 1

XMLWordPrintable

      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.

            Unassigned Unassigned
            rbair Richard Bair (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: