dequick
dequick

Reputation: 1

Why tests in Java each time goes faster?

I have a little question about Java optimization. I have a code:

import java.util.LinkedList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        int testCount = 1_000_000;

        test(testCount);
        test(testCount);
        test(testCount);
    }

    public static void test(int test) {
        List list = new LinkedList();
        long start = System.currentTimeMillis();
        for (int i = 0; i< test; i++) {
            list.add(0, i);
        }
        long finish = System.currentTimeMillis();
        System.out.println("time  " + (finish-start));
    }
}

Each next iteration of this test much less than previous.

time  2443 
time  924
time  143

Could you help me to understand why does it happen?

Upvotes: 0

Views: 73

Answers (3)

Crazyjavahacking
Crazyjavahacking

Reputation: 9687

You are experiencing the process of warming-up JVM and kicking in various performance optimizations, including inlining.

Upvotes: 1

void
void

Reputation: 7880

Why tests in Java each time goes faster?

you even can not say: tests in Java each time goes faster because it is not correct, just test it again more (i.e. see this demo) so you can't ask for the why of a incorrect statement.

the time of execution of Java programs depends on many other conditions i.e. the situation of CPU, RAM, OS, etc and of course the time of execution of specific code maybe is different each time but we can't say it goes better per each execution.

Upvotes: 0

borchero
borchero

Reputation: 6002

The problem is actually that Java has kind of a start-up phase. The code actually really gets fast after a short period of time. That's why the first time you perform the function call lasts the longest. When performing several more calls, you will see, that the execution time will be more stable after the first few iterations.

Upvotes: 1

Related Questions