Tomas Bisciak
Tomas Bisciak

Reputation: 2841

Lambda vs anonymous inner class performance: reducing the load on the ClassLoader?

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.

Upvotes: 10

Views: 4602

Answers (2)

Daniel
Daniel

Reputation: 28084

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.

Upvotes: 10

Brett Okken
Brett Okken

Reputation: 6306

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

Upvotes: 13

Related Questions