Performance difference between Java 8 lambdas and anonymous inner classes

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

Before Java 8, lambda functionality could be achieved by using anonymous inner classes. For example:

interface Lambda {     void doStuff(); }  // ...  public void doWithCallback(Lambda callback) {     // ...     callback.doStuff(); }  // ...  doWithCallback(new Lambda {      public void doStuff() {          // ...      }  }); 

In terms of performance, is there a difference between still using this approach and using the new Java 8 lambdas?

回答1:

Oracle has posted a study comparing performance between Lambdas and anonymous classes

See JDK 8: Lambda Performance Study by Sergey Kuksenko, which is 74 slides long.

Summary: slow to warm up but when JIT inlines it worst case just as fast as anonymous class but can be faster.



回答2:

As I found, the iterating over array with Stream is working much slower (74 slides are not consider such the case). I think that it is not the only performance leaks in lambdas (guess, it will be improved in the future). The example below was running with Java 8 without any options:

    //Language is an enum      Language[] array = Language.values();     System.err.println(array.length); // 72 items     long t = System.nanoTime();     for (Language l : array) System.out.println(l.getLanguageName());     System.err.println(System.nanoTime()-t); //nano time  1864724      t = System.nanoTime();     Arrays.stream(array).forEach(v -> System.out.println(v.getLanguageName()));     System.err.println(System.nanoTime()-t); //nano time 55812625 (55812625/1864724 = 29.93 times longer)      List list = Arrays.asList(array);      t = System.nanoTime();     for (Language l : list) System.out.println(l.getLanguageName());     System.err.println(System.nanoTime()-t); //nano time 1435008      t = System.nanoTime();     list.forEach(v -> System.out.println(v.getLanguageName()));     System.err.println(System.nanoTime()-t); //nano time 1619973 (1619973/1435008 = 1.128 times longer) 


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