[英]Why is ArrayList's sort method faster than Arrays' in Java?
以下代碼的目標是對300,000個int數字進行排序。 我發現ArrayList的sort()的持續時間小於Arrays的sort()。 在內部,他們使用相同的算法進行排序。 ArrayList使用Arrays的sort()來對其元素數據進行排序。
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));
}
}
結果如下:
ArrayList排序持續時間:211
陣列持續時間:435
我檢查了ArrayList的源代碼。 它在自己的排序方法中使用Arrays.sort()。
@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++;
}
所以,在我看來,我的代碼應該顯示相同的持續時間。 但我嘗試了很多次,結果很相似。 發生了什么?
Java版本:8
操作系統:Windows 7
這是一個熱身問題 - 但究竟為什么我不知道。
使用此代碼:
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;
}
並將兩種不同的順序移動到我得到的順序:
陣列持續時間:4209
ArrayList持續時間:4570
ArrayList持續時間:6776
陣列持續時間:4684
因此,如果ArrayList
首先排序,則需要更長時間。
所以@AndyTurner的評論是正確的 - 參考我如何在Java中編寫正確的微基准測試?
Java 8 - Windows 10
他們應該是一樣的,我不知道你為什么會有不同的結果。 下面是我的代碼,我幾乎是同一時間。 對於T[]
和ArrayList<T>
它們都將調用Arrays.sort(T[], ...)
,然后使用合並排序或時間排序。
Random rand = new Random();
Integer[] array = new Integer[300000];
for (int i = 0; i < array.length; i++)
array[i] = rand.nextInt(array.length);
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(array));
long a = System.currentTimeMillis();
Arrays.sort(array, 0 ,array.length);
long b = System.currentTimeMillis();
list.sort(null);
long c = System.currentTimeMillis();
System.out.println(b - a);
System.out.println(c - b);
這是我嘗試使用Java 8的東西。注意,有一個數組是int
,一個是Integer
的數組, List
是Integer
的。 此外,使用Arrays.parallelSort()
對Integer
數組進行排序。
import java.util.*;
import java.util.stream.*;
public class TestingSorts {
public static void main(String[] args) {
long t0 = 0L;
long t1 = 0L;
// Run this procedure 10 times
for (int i = 1; i < 11; i++) {
// Create an int array and Integer List filled with random numbers
int [] intArray = IntStream.generate(() -> new Random().nextInt())
.limit(300_000)
.toArray();
Integer [] integerArray = IntStream.generate(() -> new Random().nextInt())
.limit(300_000)
.boxed()
.toArray(n -> new Integer[n]);
Integer [] integerArrayP = IntStream.generate(() -> new Random().nextInt())
.limit(300_000)
.boxed()
.toArray(n -> new Integer[n]);
List<Integer> intList = IntStream.generate(() -> new Random().nextInt())
.limit(300_000)
.boxed()
.collect(Collectors.toCollection(ArrayList::new));
// Sort the List and the arrays
t0 = System.currentTimeMillis();
intList.sort(null);
t1 = System.currentTimeMillis();
System.out.println(i + ") ArrayList<Integer> sort duration: " + (t1 - t0));
t0 = System.currentTimeMillis();
Arrays.sort(integerArray, Comparator.naturalOrder());
t1 = System.currentTimeMillis();
System.out.println(i + ") Integer[ ] sort duration: " + (t1 - t0));
t0 = System.currentTimeMillis();
Arrays.parallelSort(integerArrayP, Comparator.naturalOrder());
t1 = System.currentTimeMillis();
System.out.println(i + ") Integer[ ] PARALLEL sort duration: " + (t1 - t0));
t0 = System.currentTimeMillis();
Arrays.sort(intArray);
t1 = System.currentTimeMillis();
System.out.println(i + ") int[ ] sort duration: " + (t1 - t0));
}
}
}
結果 (在CORE i3處理器上運行的Windows 7 64位操作系統上):
1) ArrayList<Integer> sort duration: 200
1) Integer[ ] sort duration: 424
1) Integer[ ] PARALLEL sort duration: 414
1) int[ ] sort duration: 136
2) ArrayList<Integer> sort duration: 143
2) Integer[ ] sort duration: 101
2) Integer[ ] PARALLEL sort duration: 56
2) int[ ] sort duration: 33
3) ArrayList<Integer> sort duration: 124
3) Integer[ ] sort duration: 118
3) Integer[ ] PARALLEL sort duration: 96
3) int[ ] sort duration: 42
4) ArrayList<Integer> sort duration: 108
4) Integer[ ] sort duration: 102
4) Integer[ ] PARALLEL sort duration: 92
4) int[ ] sort duration: 57
5) ArrayList<Integer> sort duration: 142
5) Integer[ ] sort duration: 113
5) Integer[ ] PARALLEL sort duration: 118
5) int[ ] sort duration: 31
6) ArrayList<Integer> sort duration: 113
6) Integer[ ] sort duration: 103
6) Integer[ ] PARALLEL sort duration: 58
6) int[ ] sort duration: 32
7) ArrayList<Integer> sort duration: 115
7) Integer[ ] sort duration: 116
7) Integer[ ] PARALLEL sort duration: 57
7) int[ ] sort duration: 33
8) ArrayList<Integer> sort duration: 115
8) Integer[ ] sort duration: 115
8) Integer[ ] PARALLEL sort duration: 58
8) int[ ] sort duration: 31
9) ArrayList<Integer> sort duration: 114
9) Integer[ ] sort duration: 101
9) Integer[ ] PARALLEL sort duration: 52
9) int[ ] sort duration: 32
10) ArrayList<Integer> sort duration: 113
10) Integer[ ] sort duration: 114
10) Integer[ ] PARALLEL sort duration: 57
10) int[ ] sort duration: 32
編輯 :添加了對Integer
數組進行排序的功能。
編輯 :添加了使用並行排序對Integer
數組進行排序的功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.