Java Reference
In-Depth Information
Lazy Initialization
Much of the time, the decision about whether a particular instance variable is needed is not
as black-and-white as the previous section suggests. A particular class may need a Calendar
object only 10% of the time, but Calendar objects are expensive to create, and it definitely
makes sense to keep that object around rather than re-create it on demand. This is a case
where lazy initialization can help.
So far, this discussion has assumed that instance variables are initialized eagerly. A class that
needs to use a Calendar object (and that doesn't need to be thread-safe) might look
something like this:
public
public class
class CalDateInitialization
CalDateInitialization {
private
private Calendar calendar = Calendar . getInstance ();
private
private DateFormat df = DateFormat . getDateInstance ();
private
private void
void report ( Writer w ) {
w . write ( "On " + df . format ( calendar . getTime ()) + ": " + this
this );
}
}
To initialize the fields lazily instead, there is a small trade-off in terms of computation per-
formance—the code must test the state of the variable each time the code is executed:
public
public class
class CalDateInitialization
CalDateInitialization {
private
private Calendar calendar ;
private
private DateFormat df ;
private
private void
void report ( Writer w ) {
iif ( calendar == null
null ) {
calendar = Calendar . getInstance ();
df = DateFormat . getDateInstance ();
}
w . write ( "On " + df . format ( calendar . getTime ()) + ": " + this
this );
}
}
Lazy initialization is best used when the operation in question is only infrequently used: if
the operation is commonly used, then no memory will actually be saved (since it will always
be allocated), and there will be that slight performance penalty on a common operation.
Search WWH ::




Custom Search