2

I'm kinda starting with Java 8 and I'm wondering about some best practices. I really like how i can write inline lambdas but how does this work in the background ?

I have two cases:

Using a lambda that requires an in-scope value:

private int x;

void doIt(Stream<Integer> stream) {
    stream.map(i -> i * x).forEach(...);
}

Using a lambda that is whole on it's own:

void doIt(Stream<Integer> stream) {
    stream.map(i -> i * i).forEach(...);
}

In the latest case I could actually declare the lambda as a constant:

private static final Function<Integer, Integer> squaring = i -> i * i;

void doIt(Stream<Integer> stream) {
    stream.map(squaring).forEach(...);
}

Is there any impact on the performance or is the compiler smart enough to do what's best depending on the case ?

Crystark
  • 3,693
  • 5
  • 40
  • 61
  • 1
    Best guess: inline creates more objects. But without inline, you lose almost all of the conciseness that lambdas afford you, right? I'd take the conciseness except when you can prove you need - and get - performance out of it. – Silly Freak Sep 07 '15 at 09:53
  • 2
    Brian Goetz has [talked about this](http://blog.codefx.org/java/dev/lambdas-java-peek-hood/#Evaluation). There is unlikely to be any advantage in using a static variable. – McDowell Sep 07 '15 at 10:00
  • 2
    For non capturing lambda the compiler already does something similar. See for example: http://stackoverflow.com/questions/32310324/differences-between-using-a-method-reference-and-function-object-in-stream-opera – assylias Sep 07 '15 at 10:02
  • 1
    See also [Does a lambda expression create an object on the heap every time it's executed?](http://stackoverflow.com/q/27524445/2711488) for a simpler answer. (Or for the simplest: “Don’t cache”) – Holger Sep 07 '15 at 10:35
  • 2
    @assylias, not compiler, but `LambdaMetafactory` together with virtual machine. – Tagir Valeev Sep 07 '15 at 10:37
  • 1
    @SillyFreak Often there is some... tension between "conciseness" and "readability". The `squaring` example may be overly simple, but since *code* is intended to be read by *people* (and not by computers), assigning **names** to lambdas may not be the worst idea. Of course, the preferred way will usually be writing the lambda as a method and using a method reference instread, but it may be worth mentioning. – Marco13 Sep 08 '15 at 09:39

0 Answers0