What is lazy initialization and why is it useful?

lazy initialization python
lazy initialization c++
lazy initialization c#
lazy initialization java
lazy initialization kotlin
lazy initialization swift
lazy initialization spring
lazy initialization hibernate

What is lazy initialization of objects? How do you do that and what are the advantages?

Lazy Initialization is a performance optimization where you defer (potentially expensive) object creation until just before you actually need it.

One good example is to not create a database connection up front, but only just before you need to get data from the database.

The key reason for doing this is that (often) you can avoid creating the object completely if you never need it.

What is lazy initialization and why is it useful?, Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements. These are the most common scenarios: When you have an object that is expensive to create, and the program might not use it. In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.

As others have mentioned, lazy initialization is delaying initialization until a component or object is used. You can view lazy initialization as a runtime application of the YAGNI principle - "You ain't gonna need it"

The advantages from an application perspective of lazy initialization are that users don't have to pay the initialization time for features they will not use. Suppose you were to initialize every component of your application up front. This could create a potentially long start time - users would have to wait dozens of seconds or minutes before your application is ready to use. They're waiting on and paying for initialization of features they may never use or not use right away.

Instead, if you defer initializing those components until use time, your application will start up much quicker. The user will still have to pay the startup cost when using other components, but that cost will be amortized across the run of the program and not condensed into the beginning, and the user may associate the initialization time of these objects with the features they are using.

Lazy initialization, creates the object in advance and just after starting the application or module. Lazy initialization of an object means that its creation is deferred until it is first used. (For this topic, the terms lazy initialization and lazy instantiation are synonymous.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements.

Lazy Initialization is the concept of deferring object creation until the object is actually first used. If used properly, it can result in significant performance gains.

Personally, I've used Lazy Initialization when creating my own hand-rolled ORM in .NET 2.0. When loading my collections from the database, the actual items in the collection were lazy initialized. This meant that the collections were created quickly, but each object was loaded only when I required it.

If you're familiar with the Singleton pattern, you've probably seen lazy initialization in action as well.

public class SomeClassSingleton
{
    private static SomeClass _instance = null;

    private SomeClassSingleton()
    {
    }

    public static SomeClass GetInstance()
    {
        if(_instance == null)
            _instance = new SomeClassSingleton();

        return _instance;
    }
}

In this case, the instance of SomeClass is not initialized until it is first needed by the SomeClassSingleton consumer.

Lazy initialization Vs Eager initialization, is a performance optimization. It's used when data is deemed to be 'expensive' for some reason. For example: if the hashCode value for an object might not actually be needed by its caller, always calculating the hashCode for all instances of the object may be felt to be unnecessary. (For this topic, the terms lazy initialization and lazy instantiation are synonymous.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements.

In general computing terms, 'lazy evaluation' means to defer the processing on something until you actually need it. The main idea being that you can sometimes avoid costly operations if you turn out to not need it, or if the value would change before you use it.

A simple example of this is System.Exception.StackTrace. This is a string property on an exception, but it isn't actually built until you access it. Internally it does something like:

String StackTrace{
  get{
    if(_stackTrace==null){
      _stackTrace = buildStackTrace();
    }
    return _stackTrace;
  }
}

This saves you the overhead of actually calling buildStackTrace until someone wants to see what it is.

Properties are one way to simply provide this type of behavior.

Java Practices->Lazy initialization, Lazy class loading is an important feature of the Java runtime environment as it can reduce memory usage under certain circumstances. For example, if a part of a  Lazy Initialization is a performance optimization where you defer (potentially expensive) object creation until just before you actually need it. One good example is to not create a database connection up front, but only just before you need to get data from the database.

Lazy initialization of an object means that its creation is deferred until it is first used. (For this topic, the terms lazy initialization and lazy instantiation are synonymous.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements. These are the most common scenarios:

When you have an object that is expensive to create, and the program might not use it. For example, assume that you have in memory a Customer object that has an Orders property that contains a large array of Order objects that, to be initialized, requires a database connection. If the user never asks to display the Orders or use the data in a computation, then there is no reason to use system memory or computing cycles to create it. By using Lazy to declare the Orders object for lazy initialization, you can avoid wasting system resources when the object is not used.

When you have an object that is expensive to create, and you want to defer its creation until after other expensive operations have been completed. For example, assume that your program loads several object instances when it starts, but only some of them are required immediately. You can improve the startup performance of the program by deferring initialization of the objects that are not required until the required objects have been created.

Although you can write your own code to perform lazy initialization, we recommend that you use Lazy instead. Lazy and its related types also support thread-safety and provide a consistent exception propagation policy.

Example of lazy-init in Spring, Lazy initialization is useful when calculating the value of the field is time consuming and you don't want to do it until you actually need the value. So it's often  Spring Boot 2.2 introduces support for lazy initialization and makes it easier via the introduction of a new property i.e. spring.main.lazy-initialization. When it set to true, the bean definitions across the application will be configured to use lazy initialization. Default it sets to false. Lazy Initialization

Java Tip 67: Lazy instantiation, See also. System.Threading.LazyInitializer · Lazy Initialization. Related Articles. Is this page helpful? Lazy Initialization is a technique where one postpones the instantiation of a object until its first use. In other words the instance of a class is created when its required to be used for the first time. The idea behind this is to avoid unnecessary instance creation. But there are concerns related to using such approaches in a concurrent scenario.

LazyInitialization, In this example, there are two fields with lazy initialization - fHashCode and fAwards . Lazy initialization is particularly useful for GUIs which take a long time to  Lazy initialization is particularly useful for GUIs which take a long time to construct. There are several policies for GUI construction which a design may follow: always build - construct the window many times, whenever it's demanded, and do not cache the result. first-request build - construct the window once, when first requested.

How to: Perform Lazy Initialization of Objects, Sometimes it makes sense to delay initialisation for objects that are expensive. Lazy initialisation is a common practice in programming, but in  Lazy initialization is a technique that defers the creation of an object until the first time it is needed. In other words, initialization of the object happens only on demand.

Comments
  • It should go without saying, but just in case he missed it: The reason it's an optimization is because you often find you don't need to do the creation at all, and because you might save doing some work when the computer is already busy until a time when it is less busy.
  • Good comment. I've amended the answer to incorporate your point.
  • a very good (and different) use-case/reason for using Lazy is posted in the following SO question : stackoverflow.com/a/15894928/4404962 this suggestion solved exactly what we needed to solve - using Lazy as the key principal
  • Too bad I could give only +1! Good rationale, BTW.
  • YAGNI means "you ain't gonna need it[the feature, the code]". Lazy initialization is an optimization that is a feature in itself. I would rather say that it applies the other way around: unless you know for sure you need lazy initialization, don't use is, YAGNI.
  • Remove the explicit private variable setting to 'null' to improve the speed slightly further ;). Anyway, it's redundant.
  • nice point, SomeClassSingleton must be equal or lower class of SomeClass
  • I don't know if anyone reads old responses but i assume the private static get instance method should be public?
  • @Biscuit128 - I do read them, and yes it should be. I updated it just in case anybody else still reads this.
  • should not _instance = new SomeClassSingleton(); be _instance = new SomeClass(); ? or I am understanding from different perspective
  • True, but I am not sure why you would be sharing a reference to an exception among multiple threads anyway.