Reputation: 119
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
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