I was working with some Java 8 Stream
APIs. I am confused to see the performance difference between below two solutions, that are just printing the contents of Stream
.
Solution 1:
int[] array = new int[] { 0, 1, 2, 3, 4, 5 };
start = System.nanoTime();
Arrays.stream(array).forEach(System.out::println);
System.out.println((System.nanoTime() - start) / 1000000.0f);
Solution 2:
int[] array = new int[] { 0, 1, 2, 3, 4, 5 };
start = System.nanoTime();
Arrays.stream(array).forEach(new IntConsumer() {
@Override
public void accept(int value) {
System.out.println(value);
}
});
System.out.println((System.nanoTime() - start) / 1000000.0f);
For execution, Solution 1
is taking approx. 5-6 times more time than Solution 2
.
System Configuration:
- JRE:
1.8.0_101 64 bit
- OS:
Windows 10 Home 64-bit
- RAM:
4 GB
- IDE:
Eclipse Mas-1 for Java EE 64-bit
It would be helpful if someone can explain, Why there is this huge difference?
JMH Code:
public class MyBenchmark {
@Benchmark
public void solution_0() {
int[] array = new int[] { 0, 1, 2, 3, 4, 5 };
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);asdasdas
}
}
@Benchmark
public void solution_1() {
int[] array = new int[] { 0, 1, 2, 3, 4, 5 };
Arrays.stream(array).forEach(new IntConsumer() {
@Override
public void accept(int value) {
System.out.println(value);
}
});
}
@Benchmark
public void solution_2() {
int[] array = new int[] { 0, 1, 2, 3, 4, 5 };
Arrays.stream(array).forEach(System.out::println);
}
}