DEV Community

Albert Bennett
Albert Bennett

Posted on

10 2

Lazy vs Eager Initialization

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; }
    }
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Or if you are old skool (⌐■_■)

MassiveObject bigObject = new MassiveObject ();
Enter fullscreen mode Exit fullscreen mode


Thanks for reading my post and I'll see you next time
ᕕ( ᐛ )ᕗ

Image of AssemblyAI tool

Transforming Interviews into Publishable Stories with AssemblyAI

Insightview is a modern web application that streamlines the interview workflow for journalists. By leveraging AssemblyAI's LeMUR and Universal-2 technology, it transforms raw interview recordings into structured, actionable content, dramatically reducing the time from recording to publication.

Key Features:
🎥 Audio/video file upload with real-time preview
🗣️ Advanced transcription with speaker identification
⭐ Automatic highlight extraction of key moments
✍️ AI-powered article draft generation
📤 Export interview's subtitles in VTT format

Read full post

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay