Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation differences/optimizations between Lambda Expressions and Anonymous Classes

Lets assume i want to iterate over a collection of objects.

List<String> strmap = ...
//Without lambdas
strmap.stream().filter(new Predicate<String>() {
      public boolean test(String string) {
          return string.length == 10;
      }
}.forEach(new Consumer<String>() {
      public void accept (String string) {
          System.out.println("string " + string + " contains exactly 10 characters");
      }
} 
//With lambdas
strmap.stream()
      .filter(s -> s.length == 10)
      .forEach(s -> System.out.println("string " + s + " contains exactly 10 characters");

How does the second example (without lambdas) work? A new object (Predicate and Consumer) created every time i call the code, how much can java jit compiler optimalize a lambda expression? For a better performace should i declare all lambdas as a variable and always only pass a reference?

private Predicate<String> length10 = s -> s.length == 10;
private Consumer<String> printer = s -> { "string " + s + " contains exactly 10 characters"; }

strmap.stream()
      .filter(length10)
      .forEach(printer);
like image 878
user2749903 Avatar asked Sep 02 '15 18:09

user2749903


1 Answers

How does the second example (without lambdas) work? A new object (Predicate and Consumer) created every time i call the code, how much can java jit compiler optimalize a lambda expression? For a better performace should i declare all lambdas as a variable and always only pass a reference?

The job of the JIT is to make it so you don't have to worry about any of this. For example, the JIT may (and, I believe, will) make it so that s -> s.length == 10 automatically becomes a static constant, so it's reused across the entire class, not just that instance. It might even get reused across other classes that use the same lambda somewhere else.

The entire point of lambdas is that you should just write the simplest code that makes sense and the JIT has the freedom to do whatever it needs to to make that efficient. For example, that's why lambdas are generated using invokedynamic instead of being simply desugared to anonymous inner classes in the first place.

Write the straightforward code; trust the JIT to do the right thing. That's what it's there for. That said, if you want the overwhelming, complicated nitty-gritty details, this is almost certainly the best source.

like image 183
Louis Wasserman Avatar answered Sep 17 '22 18:09

Louis Wasserman