What is lazy initialization and why is it useful?

.Net

.Net Problem Overview


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

.Net Solutions


Solution 1 - .Net

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.

Solution 2 - .Net

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.

Solution 3 - .Net

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.

Solution 4 - .Net

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.

Solution 5 - .Net

Here you can read about Lazy Initialization with sample code.

> - 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.

Solution 6 - .Net

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.

Solution 7 - .Net

//Lazy instantiation delays certain tasks. 
//It typically improves the startup time of a C# application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LazyLoad
{
    class Program
    {
        static void Main(string[] args)
        {
            Lazy<MyClass> MyLazyClass = new Lazy<MyClass>(); // create lazy class
            Console.WriteLine("IsValueCreated = {0}",MyLazyClass.IsValueCreated); // print value to check if initialization is over

            MyClass sample = MyLazyClass.Value; // real value Creation Time
            Console.WriteLine("Length = {0}", sample.Length); // print array length

            Console.WriteLine("IsValueCreated = {0}", MyLazyClass.IsValueCreated); // print value to check if initialization is over
            Console.ReadLine();
        }
    }

    class MyClass
    {
        int[] array;
        public MyClass()
        {
            array = new int[10];

        }

        public int Length
        {
            get
            {
                return this.array.Length;
            }
        }
    }
}


// out put

// IsValueCreated = False
// Length = 10
// IsValueCreated = True

Solution 8 - .Net

As what I have understood about lazy init so far, is that the program does not load/request all data a once. It waits for the use of it before requesting it from eg. a SQL-server.

If you have a database with a large table joined with a large amount of subtables and you dont require the details joined from the other tabels unless going into "edit" or "view details", then Lazy Init. will help the application to go faster and first "lazy load" the detailsdata upon needed.

In SQL or LINQ you can set this "setting" on your database model pr. dataelement.

Hope this makes any sense to your question?

A webclient (eg. a browser) does the same thing. The images are "lazy loaded" after the HTML and AJAX is also a "sort of lazy init" if used right.

Solution 9 - .Net

The database examples that have been mentioned so far are good, but it's not restricted to just the data access layer. You could apply the same principles to any situation where performance or memory can be a concern. A good example (although not .NET) is in Cocoa, where you can wait until the user requests a window to actually load it (and its associated objects) from the nib. This can help keep memory usage down and speed up the initial application load, especially when you're talking about things like Preferences windows that won't be needed until some later time, if ever.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSNAView Question on Stackoverflow
Solution 1 - .NetBevanView Answer on Stackoverflow
Solution 2 - .NetMichaelView Answer on Stackoverflow
Solution 3 - .NetJustin NiessnerView Answer on Stackoverflow
Solution 4 - .NetDolphinView Answer on Stackoverflow
Solution 5 - .NetAmir RezaeiView Answer on Stackoverflow
Solution 6 - .NetRakesh KumarView Answer on Stackoverflow
Solution 7 - .NetKarthik Krishna BaijuView Answer on Stackoverflow
Solution 8 - .NetBerggreenDKView Answer on Stackoverflow
Solution 9 - .NetMarc CharbonneauView Answer on Stackoverflow