class DummyInteger {
private int i;
public DummyInteger(int i) {
this.i = i;
}
public int getI() {
return i;
}
}
long start = System.nanoTime();
DummyInteger n = new DummyInteger(10);
long end = System.nanoTime();
long duration = end - start;
System.out.println(duration);
The previous code produces the following output:
341000
Whereas:
long start = System.nanoTime();
ArrayList a = new ArrayList();
long end = System.nanoTime();
long duration = end - start;
System.out.println(duration);
produces the following output:
17000
Now, my question is, why do we observe such difference in the running time, even though the work done by the DummyInteger
Class seems to be at most as much as that performed by the ArrayList
constructor? Does it have to do with ArrayList's code being precompiled? or is it some other factor that's affecting the processing time?
Thank you.
--EDIT--
I thought the issue of comparing two different types of objects would arise, however, even with the following code, compared to creating an ArrayList
that is:
class IntList {
int [] elementData;
public IntList() {
elementData = new int [20];
}
}
long start = System.nanoTime();
IntList n = new IntList();
long end = System.nanoTime();
long duration = end - start;
System.out.println(duration);
The result is still the same, bearing in mind, that in this case, the overhead by the creation of the ArrayList
should be greater, due to certain checks that are performed, and could be found by going through the source code.
One more thing to note, is that, I run both codes on two different runs, which eliminates any overhead that may result from the initialisation of the JVM.