"Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program's operation if properly and appropriately used. The opposite of lazy loading is eager loading."-- wikipedia
You want to be as lazy as possible, and hope that someone else comes along and does all the work for you.
This dog is doing it right
Lazy loading really means waiting to get data or process an object until you need it; not before. If you get data before and it's never used, the time it took was wasted. Also, getting all your data up front can make the user think the application is slow or unresponsive at first. Deferring certain data/processing to lazy load lets your application focus on more immediate/important code.
There are four common implementations:
Probably the most common implementation
ExampleA virtual proxy object shares an interface with the "real" object. The first time a property of the virtual proxy is accessed, the real object gets initialized. From that point on, accessing properties of the virtual object returns the corresponding property of the real object.
This basically combines the Lazy initialization and Proxy patterns
ExampleThe object is partially loaded, usually only with its identifier. The rest of the data is loaded the first time a property is accessed.
ExampleAnother object handles the lazy loading behavior and is used in the main object's property get accessors.
private ValueHolder<Widget> valueHolder;
public Widget MyWidget
{
get
{
return valueHolder.GetValue();
}
}
.NET 4.0 has a class just for lazy initialization!
MSDNYou specify the type of the object (type parameter) and the initialization function (constructor parameter) and it works like Nullable<T>, giving you IsValueCreated and Value properties.
IQueryable
/IEnumerable
uses a variation of lazy loading called "deferred execution" - it's methods are accessible, but the data is not populated until it's realized by a ToArray()
or other method call.User.Address.City
too bad we're out of time