Lazy Initialization in C#

3/28/2018 Lazy Initialization C# .NET

If you are looking for create applications with better performance, you must design and plan for performance just as you would design any other feature of your app. You can use the Microsoft tools for measure your app's performance such as Visual Studio Performance Analysis, Windows Phone Application Analysis, PerfView and Windows Performance Analyzer. One of the methods for create applications with more performance is Lazy Initialization.

Lazy initialization of an object means that its creation is deferred until it is first used. Both of Lazy Initialization and lazy instantiation terms are the same.This technique is the mainly used to improve performance, reduce program memory requirements and avoid wasteful computation.

The following items are the most common scenarios:

  • When you have an object that is expensive to create, and the program might not use it. not used.
  • When you have an object that is expensive to create, and you want to defer its creation until after other expensive operations have been completed.

The following table lists the types that the .NET Framework version 4 provides to enable lazy initialization in different scenarios.

  1. Lazy<T>
  2. ThreadLocal<T>
  3. LazyInitializer

In this article I will describe how to use Lazy<T> in you application. In fact the System.Lazy<T> class simplifies the work for performing lazy initialization and instantiation objects.

Example

The following example shows how to initialize a value with Lazy<T>. Assume that the lazy variable might not be needed, depending on some other code that sets the [myCondition] variable to true or false.

 

static bool myCondition = false;    
  //Initializing a value with a big computation, computed in parallel  
  Lazy<int> _data = new Lazy<int>(delegate  
  {  
      return ParallelEnumerable.Range(0, 1000).  
          Select(i => Compute(i)).Aggregate((x,y) => x + y);  
  }, LazyExecutionMode.EnsureSingleThreadSafeExecution);  

  // Do some work that may or may not set someCondition to true.  
  //  ...  
  // Initialize the data only if necessary  
  if (myCondition)  
  {  
    if (_data.Value > 100)  
    {  
          Console.WriteLine("Good data");  
    }  
  }

Example

The following example shows how to use the System.Threading.ThreadLocal<T> class to initialize a type that is visible only to the current object instance on the current thread.

//Initializing a value per thread, per instance
 ThreadLocal<int[][]> _scratchArrays = 
     new ThreadLocal<int[][]>(InitializeArrays);
// . . .
 static int[][] InitializeArrays () {return new int[][]}
//   . . .
// use the thread-local data
int i = 8;
int [] tempArr = _scratchArrays.Value[i];