Java Reference
In-Depth Information
usage has very little impact on performance. There is a very small cost to allocate (and, more
important, initialize) the objects, and because they are discarded quickly they do not really
slow down the garbage collector.
Nonetheless, cases can be constructed where that allocation matters and where it is better to
reuse those objects:
private IntegerInterface a1 = new
new IntegerInterface () {
public int
int getInt () {
return 1 ;
... Similarly for
for the other interfaces ....
public void
void calc () {
return a1 . get () + a2 . get () + a3 . get ();
The typical usage of the lambda does not create a new object on each iteration of the
loop—making this an area where some corner cases can favor the performance of the lambda
usage. Nonetheless, it is difficult to construct even microbenchmarks where these differences
Lambda and Anonymous Classloading
One corner case where this difference comes into play is in startup and classloading. It is
tempting to look at the code for a lambda and conclude that it is syntactic sugar around creat-
ing an anonymous class (particularly since, in the long run, their performance is equal). But
that is not how it works—the code for a lambda creates a static method that is called through
a special helper class in JDK 8. The anonymous class is an actual Java class—it has a separ-
ate class file and will be loaded from the classloader.
As we saw previously in this chapter, classloading performance can be important, particu-
larly if there is a long classpath. If this example is run such that every execution of the
calc() method is performed in a new classloader, the anonymous class implementation is at
a disadvantage. Table 12-9 shows the difference in that case.
Search WWH ::

Custom Search