- It is an on-demand loading which provides an efficient technique to improve performance.
- The opposite of lazy loading is eager loading.
Lazy Initialization
- With lazy initialization, the object to be lazily loaded is initially set to null.
- Every request for the object checks for null and creates it "on the fly" before returning it first.
- This method is the simplest to implement.
- However, if null is a legitimate return value, it may be necessary to use a placeholder object to signal that it has not been initialized.
private Widget _MyWidget = null;
public Widget MyWidget
{
get
{
if (_MyWidget == null)
_MyWidget = Widget.Load();
return _MyWidget;
}
// Or with the null-coalescing operator ??
// get => _MyWidget ?? Widget.Load();
}
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.
Lazy<T>
class implements a generic value holder.
private ValueHolder<Widget> valueHolder;
public Widget MyWidget => valueHolder.GetValue();
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.
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.
- The proxy actually is not virtual, but it is dynamic and it follows real proxy pattern.
- The virtual proxy is mostly used in ORM tools.
- It derives from the entity and overrides navigation properties.
- The proxy holds a state of navigation property in private field or any more complex structure.
- If the property is accessed first time it sees that the state is unloaded and triggers loading from database and change the state to loaded.