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);
}
}
You are measuring the instantiation of method reference, not its runtime performance.
On the first use of method reference (System.out::println
) JVM needs to create an internal class which implements IntConsumer
interface. Of course, this takes time. Though this is done only once during application lifetime.
In the second case you've made such anonymous class yourself.
If you wish to measure the runtime performance of method references, you have to revise the benchmarking metodology. See "How do I write a correct micro-benchmark in Java?"
来源:https://stackoverflow.com/questions/39947622/why-system-outprintln-is-slower-than-anonymous-class-implementation-in-java-8