Wednesday, January 15, 2014

Lazy Initialization

Lazy initialization is an amazing feature which is introduced with .NET 4.0


Lazy initialization means delaying initialization until a object or component is used.

Advantages.
* Improve performance
* Avoid wasteful computations
* Reduce program memory requirements

Real life situations for apply.

Users don't have to pay initialization time for features they will not use. Suppose you were initialize some components of your application up front. This will slowdown the application startup and users would have to wait dozens of seconds or minutes before application is ready to use.They are waiting on initialization of features that they may never use or not use right away.

If you defer initializing those components until its use time, your application will start up much quicker.

Quick demo :-

Classes :

    public class Subject{string id;}

    public class Student
    {
        private readonly Lazy<Subject> lazySubjects;
        private readonly Subject subject;

        public int Id { get; set; }
        public string Name { get; set; }

        public Subject LazySubject
        {
            get { return this.lazySubjects.Value; }
        }

        public Subject Subject
        {
            get { return this.subject; }
        }

        public Student()
        {
            lazySubjects = new Lazy<Subject>();
            subject = new Subject();
        }
    }

Test method :

 public MainWindow()
        {
            //Create Student object as lasy initialization
            Lazy<Student> studentObject = new Lazy<Student>(true);

            //Check whether Student object is actually created or not
            bool isStudentCreated = studentObject.IsValueCreated;

            //Sets the id of the Student
            studentObject.Value.Id = 1;

            //Check whether Student object is actually created after getting the customer Id
            bool isStudentCreatedFinish = studentObject.IsValueCreated;
        }

Here you can see the object is not getting initialized until you are accessing it.

Reference : http://msdn.microsoft.com/en-us/library/dd997286(v=vs.110).aspx

No comments:

Post a Comment