2017년 5월 31일 수요일

[Links] 초기화 지연(Lazy Initialization)

Object initiation 같은 부분은 안전빵으로 static으로 선언해서 사용하는 편이라.. 초기화 시점에서의 overhead와 memory footprint가 좀 걱정이 되었는데 좀 사용해 봐야 겠음.

Lazy Initialization

https://msdn.microsoft.com/ko-kr/library/dd997286(v=vs.110).aspx

형식설명
Lazy<T>클래스 라이브러리 또는 사용자 정의 형식을 위한 초기화 지연 의미 체계를 제공하는 래퍼 클래스
ThreadLocal<T>스레드 로컬 방식으로 초기화 지연 의미 체계를 제공한다는 점을 제외하면 Lazy<T>와 비슷합니다. 모든 스레드에서 자체의 고유한 값에 액세스할 수 있습니다.
LazyInitializer클래스 오버헤드 없는 개체의 초기화 지연을 위한 고급 static(Visual Basic의 경우 Shared) 메서드를 제공합니다.
사용시점에 초기화 됨.

            // Initialize by using default Lazy<T> constructor. The 
            // Orders array itself is not created yet.
            Lazy<Orders> _orders = new Lazy<Orders>();

https://msdn.microsoft.com/en-us/library/dd460709(v=vs.110).aspx


  static bool someCondition = 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 (someCondition)  
{  
    if (_data.Value > 100)  
      {  
          Console.WriteLine("Good data");  
      }  
}  


이런것도 가능하구나...

                    //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];

간단한 예제와 실제 디버깅.

http://www.c-sharpcorner.com/UploadFile/dacca2/implement-lazy-loading-in-C-Sharp-using-lazyt-class/


댓글 없음:

댓글 쓰기