Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance difference between Java 8 lambdas and anonymous inner classes

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?

like image 540
csvan Avatar asked Jun 18 '14 20:06

csvan


People also ask

Which is better lambda expression or anonymous inner class?

Lambda expression can be used where a class implements a functional interface to reduce the complexity of the code. An inner anonymous class is more powerful as we can use many methods as we want, whereas lambda expression can only be used where an interface has only a single abstract method.

Are lambdas faster in Java?

I've seen a lot of questions here about Java lambdas performance, but most of them go like "Lambdas are slightly faster, but become slower when using closures" or "Warm-up vs execution times are different" or other such things.

What is the difference between lambda vs anonymous class?

Anonymous class is an inner class without a name, which means that we can declare and instantiate class at the same time. A lambda expression is a short form for writing an anonymous class. By using a lambda expression, we can declare methods without any name.

Does lambda expression improve performance?

Oracle claims that use of lambda expressions also improve the collection libraries making it easier to iterate through, filter, and extract data from a collection. In addition, new concurrency features improve performance in multicore environments.


1 Answers

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.

like image 160
dkatzel Avatar answered Oct 06 '22 06:10

dkatzel