Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is System.Lazy<T> and the Singleton Design Pattern

Can anyone help me to understand the benefit of using System.Lazy with Singleton Design Pattern.

like image 801
Vijjendra Avatar asked Mar 10 '12 06:03

Vijjendra


People also ask

What is lazy Singleton?

One of the use cases for the Singleton pattern is lazy instantiation. For example, in the case of module imports, we may accidently create an object even when it's not needed. Lazy instantiation makes sure that the object gets created when it's actually needed.

What is singleton pattern design pattern?

Definition: The singleton pattern is a design pattern that restricts the instantiation of a class to one object. Let's see various design options for implementing such a class. If you have a good handle on static class variables and access modifiers this should not be a difficult task.

What is lazy and early loading of Singleton?

Singleton Class in Java using Lazy LoadingThe instance could be initialized only when the Singleton Class is used for the first time. Doing so creates the instance of the Singleton class in the JVM Java Virtual Machine during the execution of the method, which gives access to the instance, for the first time.

What is the main advantage of lazy loading instead eager loading for a Singleton?

The lazy loading improves the performance of an application if it is used properly. We can use the Lazy keyword to make the singleton instance lazy loading.


2 Answers

The best source on C# Singletons (also covers Lazy<>) belongs to Jon Skeet: http://csharpindepth.com/Articles/General/Singleton.aspx

Suppose you want to have a class that :

  • represents a unique resource, so it should have a unique instance,
  • the instance needs an expensive initialization,
  • the initialization parameters will be available only at the run-time,
  • there are cases which you will not use the object after all,
  • there are more than one threads that could try to initialize the singleton object simultaneously,
  • etc.

If most of the above conditions are true, you will need to ensure that the class is Singleton, and the unique instance is lazily initialized (not initialized until needed) If you target C# 4.0 or later, using Lazy<> makes your design simpler, more readable and easier to remember.

like image 162
Ali Ferhat Avatar answered Nov 22 '22 11:11

Ali Ferhat


The docs say

Use an instance of Lazy(Of T) to defer the creation of a large or resource-intensive object or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program.

So you make the singleton instance only if you need it.

Lazy instantiation is useful generally so that all the creation costs are not paid when the application insitialises - may give a nicer user experience.

like image 24
djna Avatar answered Nov 22 '22 12:11

djna