Arrays.sort() or Collections.sort() ? Which one is better to use?

Always using Arrays.sort() gives better performance .
Because, when we call Collections.sort() , it internally converts the list into an array & then sorts the list using method Arrays.sort().

Here is the practical example :

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Sort {

 public static void main(String[] args) {
  //sorted using Collections.sort()
  List aList = new ArrayList<>();
  for(int i =10000000;i>=0;i--)
  {
   aList.add(i);
  }
  long t1 = System.currentTimeMillis(); 
  Collections.sort(aList);
  long t2 = System.currentTimeMillis();
  System.out.println("Time Required using Collections.sort() :: "+(t2-t1)+"ms");
  
  //sorted using Arrays.sort()
  List bList = new ArrayList<>();
  for(int i =10000000;i>=0;i--)
  {
   bList.add(i);
  }
  long t3 = System.currentTimeMillis(); 
  Arrays.sort(bList.toArray());
  long t4 = System.currentTimeMillis();
  System.out.println("Time Required using Arrays.sort() :: "+(t4-t3)+"ms");
  
 }

}


The output for the former one is : 153 ms & that for the later is 76 ms for me.
So, now you know, Using Arrays.sort() is much better than using Collections.sort().


Happy Learning!!

1 comment :

  1. try , seeing the code implementation .... Collections.sort() converts to list using listIterator and calls Arrays.sort internally ... so the time 153ms = time to convert + sort

    ReplyDelete