Java Magazine, March/April 2016
ORACLE COM JAVAMAGAZINE MARCH APRIL 2016 28 inside java The Java core libraries community has been working hard to improve the Java Collections Framework by making it lazier Laziness in software is an architectural or systematic approach that defers producing a result until it can be definitively determined that the result is needed Many operations can be decomposed into a collection of suboperations Laziness delays performing suboperations until the results of those operations are needed to complete some other suboperation or the overall operation A nonlazy approach to completing any operation is to perform the entire sequence of suboperations and then combine their results to produce the final result The more eficient lazy approach is to begin by combining the results of suboperations Whenever you discover a needed missing result from an unsolved suboperation you perform that suboperation to determine the subresult Initially you start with no computed subresults and accumulate results by completing suboperations enabling additional suboperations to be completed and culminating in a final result for the whole operation Laziness successfully saves time if when you have the result of an operation there were suboperations whose results were never determined because those values were not needed to determine the final operation result Anytime that the result of an operation is potentially or likely not going to be needed as part of a final result it makes sense to defer that operation until it is determined that the result is actually needed The most common example of laziness occurs in expression evaluation Consider the following code int x 5 int y 3 if x 2 y 7 The simplest way to evaluate this expression would be to evaluate each term and combine the terms 5 2 FALSE 3 7 TRUE FALSE TRUE FALSE Notice that if the first term evaluates to false then the result of the entire expression will always be false Therefore we need not bother evaluating the second term unless the first term evaluates as true For Java programs the Java Language Specification specifies that terms of an expression are evaluated left to right and any terms not needed for the result will not be evaluated at all This often saves computation It is also very useful MIKE DUIGOU For Faster Java Collections Make Them Lazy How adding lazy operations to ArrayList and HashMap improved performance and reduced memory usage
You must have JavaScript enabled to view digital editions.