Java Reference
In-Depth Information
public int
int getInt () {
return 3 ;
sum = a1 . get () + a2 . get () + a3 . get ();
That is compared to the following code using lambdas:
public void
void calc () {
IntegerInterface a3 -> { return
return 3 };
IntegerInterface a2 -> { return
return 2 };
IntegerInterface a1 -> { return
return 1 };
sum = a3 . get () + a2 . get () + a1 . get ();
The body of the lambda or anonymous class is crucial here: if that body performs any signi-
ficant operations, then the time spent in the operation is going to overwhelm any small dif-
ference in the implementations of the lambda or the anonymous class. However, even in this
minimal case, the time to perform this operation is essentially the same, as Table 12-8 shows.
Table 12-8. Time to execute the calc() method using lambdas and anonymous classes
Time in microseconds
Anonymous classes 87.2
Numbers always look impressively official, but we can't conclude anything from this other
than that the performance of the two implementations is basically equivalent. That's true be-
cause of the random variations in tests, but also because these calls are measured using Sys-
tem.nanoTime() . Timing simply isn't accurate enough to believe at that level; what we do
know is that for all intents and purposes, this performance is the same.
One interesting thing about the typical usage in this example is that the code that uses the an-
onymous class creates a new object every time the method is called. If the method is called a
lot (as of course it must be in a benchmark to measure its performance), many instances of
that anonymous class are quickly created and discarded. As we saw in Chapter 5 , that kind of
Search WWH ::

Custom Search