I'm runnning some tests (very basic, nothing fancy) in order to check performance on Java 8 streams and lambdas. Using an ArrayList
of 10 million POJOS, all I want to do is get the average value of a BigDecimal
field. In order to take more than one sample, I run the process five times, and to my surprise the first of those five runs is extremely slower than the rest. I'm getting values like 0.38 seconds the first time, and 0.04 seconds on the other four. This is 10x faster!!! I also did the same test using old school for(Pojo p : pojos)
with similar results. Why is this happening, and how can I take advantage of it? The code I'm using is:
for (int i = 0; i < 5; i++) {
long init = System.nanoTime();
BigDecimal sum = lista.parallelStream().map(x -> x.getCosto()).reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal avg = sum.divide(BigDecimal.valueOf(registros));
long end = System.nanoTime();
System.out.println("End of processing: " + avg + " in "
+ ((end - init) / 1000000000.0) + " seconds.");
}