Why is Arraylist.add() of Java 8 faster than Java 17?

124 views Asked by At

When I use the Arraylist.add() method in a large loop, Java 8 is faster than Java 17.

That's why? Is this because of the method calculateCapacity(Object[] elementData, int minCapacity)?

This is my code:

public class T2 {
    static Map<String, Object> map = new HashMap<>();

    static {
        map.put("key", "value");
    }

    // loop for 10000000 times
    public static long TIMES = 10000000;

    /**
     * run with jdk17 and jdk8
     * @param args
     */
    public static void main(String[] args) {
        long l1 = 0;
        int ii = 10;
        for (int i = 0; i < ii; i++) {
            StopWatch s = new StopWatch();
            s.start();
            t3();
            s.stop();
            l1 += s.getTotalTimeMillis();
            System.out.println(s.getTotalTimeMillis());
            System.out.println(s.prettyPrint());
        }
        System.out.println("loop" + ii + "times");
        System.out.println("Average time :" + l1 / ii+"ms");
    }

    static void t3() {
        Object o = map.get("key");
        List<String> s = new ArrayList<>();
        for (int i = 0; i < TIMES; i++) {
            s.add(o.toString());
        }
    }
}

I have run this with Windows 11 and macOS, achieving the same results: Java 8 is faster than Java 17.

0

There are 0 answers