研究了下ArrayList集合的ensureCapacity方法,效率问题不太明白
为什么同样的容量,后两种的效率差这么多?
ArrayList<Integer> list = new ArrayList<>();
final int N = 10000000;
long startTime = System.currentTimeMillis();
for (int i = 0; i < N; i++) {
list.add(i);
}
long endTime = System.currentTimeMillis();
System.out.println("使用ensureCapacity方法前:" + (endTime - startTime));
list = new ArrayList<>();
long startTime1 = System.currentTimeMillis();
list.ensureCapacity(N);
for (int i = 0; i < N; i++) {
list.add(i);
}
long endTime1 = System.currentTimeMillis();
System.out.println("使用ensureCapacity方法后:" + (endTime1 - startTime1));
list = new ArrayList<>(N);
long startTime2 = System.currentTimeMillis();
// list.ensureCapacity(N);
for (int i = 0; i < N; i++) {
list.add(i);
}
long endTime2 = System.currentTimeMillis();
System.out.println("使用构造方法后:" + (endTime2 - startTime2));
使用ensureCapacity方法前:1652
使用ensureCapacity方法后:294
使用构造方法后:1197