If you liked what you read feel free to connect with me on linkedin or follow me on dev.to :)
Hi and welcome,
Today I'm going to go though the uses and differences of Lazy vs Eager initializing of objects.
As a bit of a disclaimer, I haven't seen lazy objects being used too often nowadays. Today was the first time that I had seen it in about 4 or so years but, I thought that it was an interesting topic to write a blog on.
Introduction
What Lazy initializing of an object means is to initialize an object when it is first accessed, instead of eager initializing an object.
Pros and Cons of using Lazy Initializing
Below are a few of the advantages and disadvantages of using Lazy initialization vs Eager initialization.
- pro: Lazy initializing an object can save on resources (memory and computation mostly).
- pro: With lazy initializing you can defer the instantiation of the object. For example you can instantiate a large object or collection after some intensive processing which can help improve overall performance by free up resources.
- con: It's a bit overkill if the object that you are lazy loading is small and you know that you will need to use it soon after it has been defined.
- con: Can waste lots of resources if managed incorrectly such as wrapping many small objects instead of managing them in a Lazy enumerable object or statically.
Code Sample
See below for how you can define a lazy object in C#:
public class TestLazyInitialization
{
Lazy<MassiveObject> bigObject;
public MassiveObject BigObject
{
get
{
return bigObject.Value;
}
}
public void MyFunction()
{
bigObject = new Lazy<MassiveObject>(() => new MassiveObject
{
ReallyBigString = "This is a massive object"
});
}
}
public class MassiveObject
{
public string ReallyBigString { get; init; }
}
The creation of the object inside of the lazy object happens when the Value property of the lazy object (bigObject.Value) gets accessed, in this case when a consumer access the BigObject property of the TestLazyInitialization class.
Notes
- Eager initializing an object is to initialize an object when it gets defined. Something like this:
MassiveObject bigObject => new();
Or if you are old skool (⌐■_■)
MassiveObject bigObject = new MassiveObject ();
Thanks for reading my post and I'll see you next time
ᕕ( ᐛ )ᕗ
Top comments (0)