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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With