I came across huge performance difference between adding 1st and 2nd item into a collection(tried ArrayList and HashSet), but I cannot explain why. Have searched but didn't find any answer.
public class Main {
public static void main(String[] args) {
// also tried HashSet
// also tried new ArrayList<>(2)
ArrayList<String> collection = new ArrayList<>();
long t1 = System.nanoTime();
collection.add("a");
long t2 = System.nanoTime();
collection.add("b");
long t3 = System.nanoTime();
System.out.println(String.valueOf(t2 - t1) + "\n"
+ String.valueOf(t3 - t2));
//typical output:
//4399
//1201
}
}
Some guess:
- because collection is lazily initialzed when adding 1st item?
- or I used the wrong way to measure performance?
- or related to how jvm works(which is beyond my knowledge)?
Environment: jdk11, win10, intellij.