Why is creating an ArrayList with initial power slowly?

Comparing the creation of a large ArrayList with intialCapacity, I found it to be slower than creting without it. Here is a simple program that I wrote to measure it:

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());

Average result for new ArrayList<>(30000000):6121173329

Average result for new ArrayList<>():4883894100

on my car. I thought it would be faster to create a large array, rather than repeating it as soon as we go beyond the capabilities of the current base array ArrayList. In the end, we would have to have the size of the array larger or equal 30000000.

I thought it was optimization, but actual pessimization. Why?

+4
source share
1 answer

I have run the same program several times. It was not in a loop

, - " " ( , 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;
}

, .

: , - Java?

+6

Source: https://habr.com/ru/post/1650326/


All Articles