The intent of lazy loading
If you’re lazy about doing things you’ll win when it turns out you don’t need to do them at all.
Martin Fowler
The intent of this approach is to increase application performance by reducing the amount of work it has to do in situations when this work is not necessary. To put it more technically:
The intent of the Lazy Load Pattern is to interrupt an object’s loading process for the moment, leaving a marker in the object structure so that if the data is needed, it can be loaded only when it is used.
“Patterns of Enterprise Application Architecture”
by Martin Fowler
Varieties
There are several approaches to lazy loading:
- lazy initialization – uses a special marker value- which is usually null- to indicate that the field is not loaded yet. Each access to the field checks this marker value and if the field is not loaded- loads it.
- virtual proxy is an object implementing the same interface or inheriting from the same type as the real object. The first time one of its methods are called it loads the real object and then delegates.
- value holder is an object containing GetValue method which returns the real object. The first call triggers the load.
- A ghost is the real object but without any data (in a partial state). Typically it only contains its ID, so it’s very lightweight. The ghost loads the full data into its fields the first time any of its properties is accessed. The object is essentially its own virtual proxy, which eliminates some of the identity concerns that the virtual proxy solution had. However, ghost violates the Single Responsibility Principle, because this object is responsible for all the things it normally is responsible for, and the lazy loading of its state.
Lazy loading is a tuning mechanism that should be applied to increase the application’s performance. Do not put it everywhere in your app. Use it only when you need it. Extensive usage of lazy loading can in fact decrease the performance.
References
https://app.pluralsight.com/library/courses/patterns-library
https://martinfowler.com/eaaCatalog/lazyLoad.html
Picture from: https://www.pcmag.com/feature/336275/10-apps-every-lazy-person-needs