Why System.out::println is slower than anonymous class implementation in Java 8?

浪子不回头ぞ 提交于 2019-12-05 07:48:28

问题


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);
    }
}

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!