Why is Collections.sort() much slower than Arrays.sort()?

So, there are two different methods with totally different algorithms here:

Arrays.sort(int[]) uses a dual-pivot quicksort algorithm.

Collections.sort(List<T>) calls list.sort(null) which in turn calls Arrays.sort(T[]). This uses a Timsort algorithm.

So, let’s compare Arrays.sort(int[]) and Arrays.sort(T[]).

  1. T[] is a boxed array so there is one extra level of indirection: for each call, you have to unwrap Integer. This certainly leads to an overhead. On the other hand, int[] is a primitive array so all elements are available “immediately”.
  2. TimSort is a variation of a classic mergesort algorithm. It is faster than mergesort but it still slower than quicksort because
    • quicksort has fewer data movements on random data
    • quicksort requires O(log(n)) extra space while TimSort requires O(n) to provide stability which also leads to an overhead.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)