Lazy Loading Design Pattern
Last Updated :
07 Feb, 2018
Lazy loading is a concept where we delay the loading of object until the point where we need it.
- Lazy loading is just a fancy name given to the process of initializing a class when it’s actually needed.
- In simple words, Lazy loading is a software design pattern where the initialization of an object occurs only when it is actually needed and not before to preserve simplicity of usage and improve performance.
- Lazy loading is essential when the cost of object creation is very high and the use of the object is very rare. So this is the scenario where it’s worth implementing lazy loading.The fundamental idea of lazy loading is to load object/data when needed.
For Example, Suppose You are creating an application in which there is a Company object and this object contains a list of employees of the company in a ContactList object. There could be thousands of employees in a company. Loading the Company object from the database along with the list of all its employees in the ContactList object could be very time consuming. In some cases you don’t even require the list of the employees, but you are forced to wait until the company and its list of employees loaded into the memory.
One way to save time and memory is to avoid loading of the employee objects until required and this is done using the Lazy Loading Design Pattern.

There are four common implementations of Lazy Loading pattern :
- Virtual proxy
- Lazy initialization
- Ghost
- Value holder
Virtual proxy
The Virtual Proxy pattern is a memory saving technique that recommends postponing an object creation until it is needed. It is used when creating an object the is expensive in terms of memory usage or processing involved.
Output:
Company Name: ABC Company
Company Address: India
Company Contact No.: +91-011-28458965
Requesting for contact list
Fetching list of employees
Employee Name: Lokesh, EmployeeDesignation: SE, Employee Salary: 2565.55
Employee Name: Kushagra, EmployeeDesignation: Manager, Employee Salary: 22574.0
Employee Name: Susmit, EmployeeDesignation: G4, Employee Salary: 3256.77
Employee Name: Vikram, EmployeeDesignation: SSE, Employee Salary: 4875.54
Employee Name: Achint, EmployeeDesignation: SE, Employee Salary: 2847.01
Now, In the above code have a Company object is created with a proxy ContactList object. At this time, the Company object holds a proxy reference, not the real ContactList object’s reference, so there no employee list loaded into the memory.
Lazy Initialization
The Lazy Initialization technique consists of checking the value of a class field when it’s being used. If that value equals to null then that field gets loaded with the proper value before it is returned.
Here is the example :
public class ValueHolder<T> {
private T value;
private readonly Func<object, T> valueRetrieval;
public ValueHolder(Func<object, T> valueRetrieval)
{
valueRetrieval = this .valueRetrieval;
}
public T GetValue(object parameter)
{
if (value == null )
value = valueRetrieval(parameter);
return value;
}
}
|
Output :
Number of instances made = 1
BMW
Number of instances made = 2
BMW
Audi
Number of instances made = 2
BMW
Audi
Value Holder
Basically, A value holder is a generic object that handles the lazy loading behavior and appears in place of the object’s data fields.When the user needs to access it, they simply ask the value holder for its value by calling the GetValue method. At that time (and only then), the value gets loaded from a database or from a service.(this is not always needed).
$userData = array(
"UID" = > uniqid(),
"requestTime" = > microtime( true ),
"dataType" = > "" ,
"request" = > "" );
if (isset($_POST[ 'data' ]) && $userData) {
}
|
Note : The main drawback of this approach is that the user has to know that a value holder is expected.
Ghost
A ghost is the object that is to be loaded in a partial state. It corresponds to the real object but not in its full state. It may be empty or it may contain just some fields (such as the ID). When the user tries to access some fields that haven’t been loaded yet, the ghost object fully initializes itself (this is not always needed).
For example, Let’s consider that a developer what add an online form so that any user can request content via that online form. At the time of creation all we know is that content will be accessed but what action or content is unknown to the user.
In the above PHP example, the content from the online form can be accessed to the user in the form of text file or any source.
- UID is the unique id for the every particular user.
- requestTime is the time when user requested the content from the online form.
- dataType is the type of data. Mostly it is text but depends on the form.
- request is the boolean function to notify the user about the request being completed or not.
Advantages
- This approach is a faster application start-up time as it is not required to created and load all of the application objects.
Disadvantages
- The code becomes complicated as we need to check if loading is needed or not. So this may cause slower in the performance.
Similar Reads
Flyweight Design Pattern
The Flyweight design pattern is a structural pattern that optimizes memory usage by sharing a common state among multiple objects. It aims to reduce the number of objects created and to decrease memory footprint, which is particularly useful when dealing with a large number of similar objects. Table
10 min read
Design Patterns Gamma
Elements of Reusable Object-Oriented Software is a software engineering book describing software design patterns. The book was written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, with a foreword by Grady Booch. The book is divided into two parts, with the first two chapters expl
6 min read
Factory method Design Pattern
The Factory Method Design Pattern is a creational design pattern that provides an interface for creating objects in a superclass, allowing subclasses to alter the type of objects that will be created. This pattern is particularly useful when the exact types of objects to be created may vary or need
8 min read
Facade Method Design Pattern
Facade Method Design Pattern is a part of the Gang of Four design patterns and it is categorized under Structural design patterns. Before we go into the details, visualize a structure. The house is the facade, it is visible to the outside world, but beneath it is a working system of pipes, cables, a
8 min read
Null Object Design Pattern
The Null Object Design Pattern is a behavioral design pattern that is used to provide a consistent way of handling null or non-existing objects. It is particularly useful in situations where you want to avoid explicit null checks and provide a default behavior for objects that may not exist. Importa
7 min read
Iterator Design Pattern
The Iterator pattern is a widely used design pattern in software development that provides a way to access the elements of an aggregate object (such as a list or collection) sequentially without exposing its underlying representation. Table of Content What is the Iterator Design Pattern?Components o
7 min read
Mediator design pattern
The Mediator Design Pattern simplifies communication between multiple objects in a system by centralizing their interactions through a mediator. Instead of objects interacting directly, they communicate via a mediator, reducing dependencies and making the system easier to manage. Table of Content Wh
7 min read
MVC Design Pattern
The MVC design pattern is a software architecture pattern that separates an application into three main components: Model, View, and Controller, making it easier to manage and maintain the codebase. It also allows for the reusability of components and promotes a more modular approach to software dev
7 min read
Mediator Design Pattern in Java
The mediator design pattern defines an object that encapsulates how a set of objects interact. The Mediator is a behavioral pattern (like the Observer or the Visitor pattern) because it can change the program's running behavior. We are used to see programs that are made up of a large number of class
4 min read
Facade Method - C++ Design Patterns
The Facade Pattern is a design pattern in software engineering that falls under the structural pattern category. It provides a simplified and unified interface to a set of interfaces or subsystems within a larger system, making it easier to use and reducing the complexity of the system for clients.
10 min read