Jump to content

Lazy loading

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by 89.146.39.39 (talk) at 10:27, 16 March 2016 (Ghost: Fixed an error in the code. I removed the comma at the end of the associative array, because it shouldn't be there. http://www.w3schools.com/php/php_arrays.asp). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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.

Implementations

There are four common ways of implementing the lazy load design pattern: lazy initialization; a virtual proxy; a ghost, and a value holder.[1] Each has its own advantages and disadvantages.

Lazy initialization

With lazy initialization, the object to be lazily loaded is originally set to null, and every request for the object checks for null and creates it "on the fly" before returning it first, as in this C# example:

private int myWidgetID;
private Widget myWidget = null;
 
public Widget MyWidget 
{
    get 
    {
        if (myWidget == null) 
        {
            myWidget = Widget.Load(myWidgetID);
        }
        
        return myWidget;
    }
}

Or with the null-coalescing operator '??'

private int myWidgetID;
private Widget myWidget = null; 

public Widget MyWidget 
{
   get { return myWidget = myWidget ?? Widget.Load(myWidgetID);  }
}

This method is the simplest to implement, although if null is a legitimate return value, it may be necessary to use a placeholder object to signal that it has not been initialized.

Virtual proxy

Virtual Proxy is an object with the same interface as the real object. The first time one of its methods is called it loads the real object and then delegates.

Ghost

A "ghost" is the object that is to be loaded in a partial state. It may only contain the object's identifier, but it loads its own data the first time one of its properties is accessed. For example, consider that a user is about to request content via an online form. At the time of creation all we know is that content will be accessed but what action or content is unknown. PHP Example:

$userData = array (
    "UID" = > uniqid(),
    "requestTime" => microtime( true ),
    "dataType" => "",
    "request" => ""
);

if (isset( $_POST['data'] ) && $userData) {
    //...

}

Value holder

A value holder is a generic object that handles the lazy loading behavior, and appears in place of the object's data fields:

private ValueHolder<Widget> valueHolder;
 
public Widget MyWidget 
{
    get
    {
        return valueHolder.GetValue();
    }
}

See also

References

  1. ^ Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2003, pp.200-214. ISBN 0-321-12742-0.