The following code proves that method1 is faster than method2
No. This is not to prove .
It depends on many factors. When I run this code, I get
1403 1248
So, in my environment, your code "proves" that method1 is slower than method2.
When benchmarking, you need to take care of effects such as caching and JVM warm-ups.
see also
for more information.
I reorganized the main method a bit:
... static void doBenchmark() { Trial t = new Trial(); long startTime1 = System.currentTimeMillis(); t.method1(); long endTime1 = System.currentTimeMillis(); long startTime2 = System.currentTimeMillis(); t.method2(); long endTime2 = System.currentTimeMillis(); System.out.println(endTime1 - startTime1); System.out.println(endTime2 - startTime2); } public static void main(String args[]) { for (int i = 0; i < 20; i++) { doBenchmark(); System.out.println("----"); } }
This leads to similar values โโfor the first iteration of for -loop, but then the results converge and will not differ significantly:
1396 1133 ---- 1052 1070 ---- 688 711 ---- 728 726 ---- 715 709 ---- ...
Even sometimes method1 seems faster, and sometimes method2 - this is most likely due to inaccuracy of the measurement.
source share