Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is lazy instantiation

Is lazy instantiation about using less code but getting the same result? Surely this is generally a good thing to do (providing making the code to short / efficient doesn't damage readability/maintainability).

Please refer to this lazy instantiation:

public sealed class Singleton
{
    private Singleton()
    {
    }

    public static Singleton Instance { get { return Nested.instance; } }

    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
} 

There is no private property of Instance (I know it's implicit) - is it that which makes it lazy - the fact we don't have a setter within the public static Singleton Instance property?

like image 368
Dave Avatar asked Sep 25 '12 13:09

Dave


3 Answers

Lets say we have a field of a type that is expensive to construct

class Foo
{
    public readonly Expensive expensive = new Expensive();
    ...
}

The problem with this code is that instansiating Foo incurs the performance cost of instansiating Expensive - whether-or-not the Expensive field is ever accessed. The obvious answer is to construct the instance on demand or lazily instansiate the field:

class Foo
{
    Expensive _expensive;
    public Expensive
    {
        get
        {
            if (_expensive == null) _expensive = new Expensive();
            return _expensive;
        }
    }
    ...
}

This is lazy instansiation.

like image 156
MoonKnight Avatar answered Oct 21 '22 12:10

MoonKnight


Lazy initialization is a practice whereby you only load or initialize an object when you first need it.

Potentially, this can give you a big performance boost, especially if you have a vast amount of components in your application.

Look at the Wikipedia page for a greater insight (it features coded examples).

like image 36
dsgriffin Avatar answered Oct 21 '22 13:10

dsgriffin


No, lazy instantiation means not spending any time and resources creating something until you actually need it.

In your singleton example, the instance is just an empty reference, until it's actually used. When it's used, then you spend the resources to instantiate the object with a new.

like image 5
Kache Avatar answered Oct 21 '22 13:10

Kache