9

I would like to know how big of a benefit lambdas have in Java 8. I agree that it might be more readable sometimes to use lambdas, but does it have really such of a big impact on the performance side? Or is it mainly focused as syntactic sugar? I prefer anonymous inner classes sometimes; do I really lose many benefits when I don't use lambda all the time?

The only ?big? performance gain, it seems to me, is that we don't actually create classes that the class loader has to load at the start of the program -- for example creating many many threads:

Thread t = new Thread(new Runnable() {
   public.....
});

creates classes like Sample$1.class.

Other than that, is there any performance or other hidden gain besides readability or maintainability etc. of the code? Hidden somewhere in JVM? I've seen questions similiar to this but most of them were focused on visual side; I'm not interested in that. The question is out of curiosity after watching Java 8 Lambdas Hacking with Venkat Subramaniam.

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
Tomas Bisciak
  • 2,801
  • 5
  • 33
  • 57

2 Answers2

12

Oracle has a presentation covering some of the performance differences. It appears that there are quite a few factors that impact performance of lambdas vs. anonymous classes.

http://www.oracle.com/technetwork/java/jvmls2013kuksen-2014088.pdf

Brett Okken
  • 6,210
  • 1
  • 19
  • 25
9

After reading the PDF linked from @Brett Okken I believe the following holds:

  • Inner classes have a slightly slower performance on first use, but it seems negliable.
  • Lambdas have a slower performance when called often because of the bigger stack they build up when called.

I will stick with the following:

  • Use Lambdas for readability when a few milliseconds performance loss is not a problem (GUI stuff, etc.)
  • Use inner classes for often called, performance critical functions.
Daniel
  • 27,718
  • 20
  • 89
  • 133
  • 1
    Also bear in mind that lambdas don't result in object creation, so for example if you're just submitting Runnables to an Executor, you may potentially see performance improvements in time and/or memory. – Sina Madani Apr 16 '18 at 18:19
  • @SinaMadani that is true if there are no references to contextual variables. – Brett Okken Sep 19 '19 at 17:49