Lazy Loading

the Design Pattern

Definition

"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

What does that mean?

You want to be as lazy as possible, and hope that someone else comes along and does all the work for you.

Can you show me a picture?

This dog is doing it right

Wait what?

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.

Implementations

There are four common implementations:

  • Lazy initialization
  • Virtual proxy
  • Ghost
  • Value holder

Lazy initialization

Probably the most common implementation

Example

Virtual Proxy

A 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

Example

Ghost

The object is partially loaded, usually only with its identifier. The rest of the data is loaded the first time a property is accessed.

Example

Value holder

Another 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();
    }
}

System.Lazy

.NET 4.0 has a class just for lazy initialization!

MSDN

You 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.

Other examples

  • Lazy loading is frequently used with the Singleton pattern
  • 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.
  • Entity Framework and other ORMs can use lazy loading when retrieving table data joined with a foreign key. Eg: User.Address.City
  • There are tons of other examples of lazy loading - infinite scrolling, images rendered in viewport, etc.

Questions?

too bad we're out of time