0

Which of the two Java sorting methods, Collections.sort(list) or list.sort(Comparator.naturalOrder()), is more efficient?

List<Integer> list = new ArrayList<>(Arrays.asList(2, 3, 1));
    
//1.Collections
Collections.sort(list);
System.out.println(list);// [1, 2, 3]

    
//2.import java.util.Comparator;
list.sort(Comparator.naturalOrder());
System.out.println(list);// [1,2,3]

I expect that there won't be a significant performance difference when comparing the algorithms of these two methods.

  • 2
    `Collections.sort` calls `List#sort` passing it `null` - so both the same ‍♂️ – MadProgrammer Jun 10 '23 at 10:19
  • Seems it was discussed already here https://stackoverflow.com/questions/34910841/difference-between-collections-sortlist-and-list-sortcomparator – grey Jun 10 '23 at 10:26
  • It's _perhaps marginally_ more efficient to use `list.sort`, because `Collections.sort(list)` calls `list.sort()`; so you avoid one function call in the worst case, and no difference if the JIT optimized that function call away. – Andy Turner Jun 10 '23 at 10:28
  • Actually, you're sorting lists, not arrays. So use `Arrays.sort()` for arrays. Unfortunately, `Arrays.sort()` does not take a comparator for primitive arrays. So you're stuck with natural ordering. – WJS Jun 10 '23 at 14:56

0 Answers0