Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

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.

Lazy initialization of an object means that its creation is deferred until it is first used.

For complete reference see msdn post Lazy Initialization

In your above code, the instance of the singleton class is not created until you call it. So, your program will not use resources until your code gets called.

It's lazy because the instance of the class Singleton isn't created until the first time you ask for it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top