I was trying to check the time of execution with similar blocks.
Sample code and output are below,
public class Tester {
public static void main(String[] args) {
System.out.println("Run 1");
List<Integer> list = new ArrayList<>();
int i = 0;
long st = System.currentTimeMillis();
while (++i < 10000) {
list.add(i);
}
System.out.println("Time taken :" + (System.currentTimeMillis() - st));
System.out.println("Run 2");
int j = 0;
List<Integer> list2 = new ArrayList<>();
long ST = System.currentTimeMillis();
while (++j < 10000) {
list2.add(j);
}
System.out.println("Time taken :" + (System.currentTimeMillis() - ST));
System.out.println("Run 3");
int k = 0;
List<Integer> list3 = new ArrayList<>();
long ST2 = System.currentTimeMillis();
while (++k < 10000) {
list3.add(k);
}
System.out.println("Time taken :" + (System.currentTimeMillis() - ST2));
}
}
Output
Run 1
Time taken :6
Run 2
Time taken :3
Run 3
Time taken :1
Why am I getting different time of execution?