vincent ren
vincent ren

Reputation: 119

Java first time create an Object will slowly than next create this Object

I have a question about create an java object,

public static void main(String[] args) throws InterruptedException {
    for(int i =0;i<5;i++){
        long now = System.currentTimeMillis();
        RestTemplate httpClient = new RestTemplate();
        System.out.println(System.currentTimeMillis() - now);
    }
}

this result is

1084
16
7
12
5

Obviously, the first time had spent 1084ms, but second only spend 16ms. Why this happened in Java? Thank you for your help!

Upvotes: 1

Views: 108

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533492

Code is lazy loaded and classes lazily initialised. The more code which has to be loaded and classes initialised the longer it takes.

If this is a concern you can do a dummy execution of the code so the first time you use it it will be faster.

Note: at this point almost none of the code has been compiled and it can be much, much faster after it has been called enough times to be compiled.

In terms of micro-benchmarks, I would ignore the first 2-10 seconds, and the first 20,000 calls which ever takes longer.

Upvotes: 1

Related Questions