O objetivo do código a seguir é classificar 300.000 números int. Acho que a duração do tipo de ArrayList () é inferior a Arrays' sort (). Internamente, eles usam o mesmo algoritmo para classificar. ArrayList usa tipo Arrays' () para ordenar seus dados do elemento.
public class EasySort {
public static void main(String args[]) {
// Read data from file, number split by ","
FileReader fr = null;
try {
fr = new FileReader("testdata2.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader bufferedReader=new BufferedReader(fr);
String line=null;
try {
line=bufferedReader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// use split method to generate a String array to save numbers
String[] strArray=line.split(",");
//Convert string array to ArrayList<Integer>
ArrayList<Integer> integerList=new ArrayList<>();
for(String str:strArray){
integerList.add(Integer.parseInt(str));
}
//Sort by ArrayList
long t0=System.currentTimeMillis();
integerList.sort(((p1,p2)->(p1.intValue()<p2.intValue()?-1:p1.intValue()>p2.intValue()?1:0)));
long t1=System.currentTimeMillis();
System.out.println("ArrayList Sort duration:"+(t1-t0));
//Convert string array to Integer array
Integer[] integerArray=new Integer[strArray.length];
int i=0;
for(String str:strArray){
integerArray[i++]=Integer.parseInt(str);
}
//Sort by Arrays
t0=System.currentTimeMillis();
Arrays.sort(integerArray, ((p1,p2)->(p1.intValue()<p2.intValue()?-1:p1.intValue()>p2.intValue()?1:0)));
t1=System.currentTimeMillis();
System.out.println("Arrays duration:"+(t1-t0));
}
}
O resultado é o seguinte:
ArrayList Ordenar duração: 211
matrizes de duração: 435
Eu verifiquei o código-fonte do ArrayList. Ele usa Arrays.sort () em seu próprio método de classificação.
@Override
@SuppressWarnings("unchecked")
public void sort(Comparator<? super E> c) {
final int expectedModCount = modCount;
Arrays.sort((E[]) elementData, 0, size, c);
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
Então, na minha opinião, o meu código deve mostrar a mesma duração. Mas eu tentei muitas vezes, e os resultados são semelhantes. O que aconteceu?
Versão Java: 8
Sistema operacional: Windows 7
Esta é uma questão-warm up - mas exatamente por isso que eu não sei.
Usando este código:
public void test() {
Integer[] a = randomData(10000000);
ArrayList<Integer> integerList = new ArrayList<>();
for (Integer i : a) {
integerList.add(i);
}
long t0, t1;
//Sort by ArrayList
t0 = System.currentTimeMillis();
integerList.sort(((p1, p2) -> (p1.intValue() < p2.intValue() ? -1 : p1.intValue() > p2.intValue() ? 1 : 0)));
t1 = System.currentTimeMillis();
System.out.println("ArrayList duration:" + (t1 - t0));
//Sort by Arrays
Integer[] integerArray = Arrays.copyOf(a, a.length);
t0 = System.currentTimeMillis();
Arrays.sort(integerArray, ((p1, p2) -> (p1.intValue() < p2.intValue() ? -1 : p1.intValue() > p2.intValue() ? 1 : 0)));
t1 = System.currentTimeMillis();
System.out.println("Arrays duration:" + (t1 - t0));
}
Random r = new Random(System.currentTimeMillis());
private Integer[] randomData(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = r.nextInt();
}
return a;
}
e movendo-se os dois tipos em diferentes ordens eu recebo:
duração matrizes: 4209
duração ArrayList: 4570
duração ArrayList: 6776
duração matrizes: 4684
Então, se ArrayList
é classificada primeira leva mais tempo.
Então @ comentário de AndyTurner está correto - consulte Como faço para escrever uma micro-referência correto em Java?
Java 8 - Windows 10