Java Reference
In-Depth Information
private
private < T > ArrayList < T > calcArray ( ArrayLisr < T > src , Predicate < T > p ) {
ArrayList < T > dst = new
new ArrayList <>();
for
for ( T s : src ) {
iif ( p . test ( s ))
dst . add ( s );
}
return
return dst ;
}
private
private static
static long
long calcEager ( ArrayList < String > a1 ) {
long
long then = System . currentTimeMillis ();
ArrayList < String > a2 = calcArray ( a1 , ( String s ) -> s . charAt ( 0 ) != 'A' );
ArrayList < String > a3 = calcArray ( a2 , ( String s ) -> s . charAt ( 1 ) != 'A' );
ArrayList < String > a4 = calcArray ( a3 , ( String s ) -> s . charAt ( 2 ) != 'A' );
ArrayList < String > a5 = calcArray ( a4 , ( String s ) -> s . charAt ( 3 ) != 'A' );
answer = a5 . get ( 0 );
long
long now = System . currentTimeMillis ();
return
return now - then ;
}
There are two reasons this alternative is less efficient than the lazy implementation that Java
actually adopted. First, it requires the creation of a lot of temporary instances of the Ar-
rayList class. Second, in the lazy implementation, processing can stop as soon as the find-
First() method gets an element. That means only a subset of the items must actually pass
through the filters. The eager implementation, on the other hand, must process the entire list
several times until the last list is created.
Hence, it should come as no surprise that the lazy implementation is far more performant
than the alternative in this example. In this case, the test is processing a list of 456,976 four-
letter symbols, which are sorted in alphabetical order. The eager implementation processes
only 18,278 of those before it encounters the symbol BBBB , at which point it can stop. It takes
the iterator two orders of magnitude longer to find that answer, as shown in Table 12-10 .
Table 12-10. Time to process lazy versus eager filters
Implementation Seconds
Filter/ findFirst
0.359
Iterator/ findFirst 48.706
Search WWH ::




Custom Search