System.Lazy(Of T) Class


With lazy initialization, the memory for an object is not allocated until it is needed. Lazy initialization can improve performance by spreading object allocations evenly across the lifetime of a program.

With .Net 4.0 we  can enable lazy initialization for any custom type by wrapping the type inside a System.Lazy(Of T) class.

If you're familiar with the Singleton pattern, you've probably seen lazy initialization in action as well.

   public class SomeClassSingleton {

    private static SomeClass _instance = null;

    private SomeClassSingleton()  {   }

     private static SomeClass GetInstance()

    {

        if(_instance == null)

            _instance = new SomeClassSingleton(); 

        return _instance;

    } }

So instead of writing all these line we can simply use this class getting the same performance.

For example if we have a  Customer object that has an Orders property that contains a large array of Order objects that, to be initialized, requires a database connection. If the user never asks to display the Orders or use the data in a computation, then there is no reason to use system memory or computing cycles to create it.

By using Lazy<Orders> to declare the Orders object for lazy initialization, we can avoid wasting system resources when the object is not used.

// Initialize by using default Lazy<T> constructor. The

// Orders array itself is not created yet.

Lazy<Orders> _orders = new Lazy<Orders>();

 

Thanks

shinu

Up Next
    Ebook Download
    View all
    Learn
    View all