为什么创建初始容量较慢的ArrayList?

use*_*882 4 java arraylist

比较创建大型ArrayList与intialCapacity我发现它;比没有一个创建它慢.这是我编写的用于衡量它的简单程序:

long start2 = System.nanoTime();
List<Double> col = new ArrayList<>(30000000); // <--- Here
for (int i = 0; i < 30000000; i++) {
    col.add(Math.sqrt(i + 1));
}
long end2 = System.nanoTime();
System.out.println(end2 - start2);
System.out.println(col.get(12411325).hashCode() == System.nanoTime());
Run Code Online (Sandbox Code Playgroud)

新的平均结果ArrayList<>(30000000):6121173329

新的平均结果ArrayList<>():4883894100

在我的机器上.我认为创建一次大型数组会更快,而不是一旦我们超出当前底层数组的容量就重新创建它ArrayList.最终我们应该最终得到大于或等于的数组大小30000000.

我认为这是优化,但实际上是悲观.为什么?

cop*_*peg 6

我多次运行同一个程序.它不在一个循环中

考虑一下如何分析代码 - 如果你既包括'加速时间'(考虑JIT之类的东西)和平均多次调用(收集一些统计/分布),时间可能会导致你变得不同结论.例如:

public static void main(String[] args){
    //Warm up
    System.out.println("Warm up");
    for ( int i = 0; i < 5; i++ ){
        dynamic();
        constant();
    }
    System.out.println("Timing...");
    //time
    long e = 0;
    long s = 0; 
    int total = 5;
    for ( int i = 0; i < total; i++ ){
        long e1 = dynamic();
        System.out.print(e1 + "\t");
        e += e1;
        long s1 = constant();
        System.out.println(s1);
        s += s1;
    }
    System.out.println("Static Avg: " + (s/total));
    System.out.println("Dynamic Avg: " + (e/total));

}

private static long dynamic(){
    long start2 = System.currentTimeMillis();
    List<Double> col = new ArrayList<>();
    for (int i = 0; i < 30000000; i++) {
        col.add(Math.sqrt(i + 1));
    }
    long end2 = System.currentTimeMillis();
    return end2 - start2;
}

private static long constant(){
    long start2 = System.currentTimeMillis();
    List<Double> col = new ArrayList<>(30000000); 
    for (int i = 0; i < 30000000; i++) {
        col.add(Math.sqrt(i + 1));
    }
    long end2 = System.currentTimeMillis();
    return end2 - start2;
}
Run Code Online (Sandbox Code Playgroud)

在我的系统设置中,初始容量总是更快,但不是任何数量级.

编辑:正如评论中所建议的那样,请考虑阅读如何在Java中编写正确的微基准测试?