Experienced Developers, Use These Quirks to Create Better Java Lambdas
How Java lambdas beat anonymous classes’ performance
You heard these claims:
- “Lambdas are only syntactic sugar for anonymous classes!”
- “Lambdas are slow, use anonymous classes!”
- “Lambdas are the de facto solution for stream manipulation.”
Are lambdas syntactic sugar? How slow are lambdas? What’s wrong with using lambdas for stream operations?
Let’s see what is the actual truth.
Lambdas aren’t only syntactic sugar
Most Java developers believe lambdas are Java anonymous classes. They’re JVM anonymous classes under the hood.
Lambdas, with the help of indy
, are converted to function objects. IDE suggests lambda instead of anonymous classes. Even so, Java runtime doesn't just convert lambda to an anonymous class. Lambda-generated anonymous objects are different from Java anonymous objects.
Why aren’t we using inner classes? Why do we need indy?
Seems reasonable, but there are more benefits of adding new logic for lambdas. Brian Goetz states that the lazy init of lambdas trumps inner classes.