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?
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With