C#性能優化之Lazy 實現延遲初始化

  在.NET4.0中,可使用Lazy<T> 來實現對象的延遲初始化,從而優化系統的性能。延遲初始化就是將對象的初始化延遲到第一次使用該對象時。延遲初始化是咱們在寫程序時常常會遇到的情形,例如建立某一對象時須要花費很大的開銷,而這一對象在系統的運行過程當中不必定會用到,這時就可使用延遲初始化,在第一次使用該對象時再對其進行初始化,若是沒有用到則不須要進行初始化,這樣的話,使用延遲初始化就提升程序的效率,從而使程序佔用更少的內存。安全

  下面咱們來看代碼,新建一個控制檯程序,首先建立一個Student類,代碼以下:(因爲用的英文版操做系統,因此提示都寫成英文,還請見諒)多線程

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
   public class Student
   {
      public Student()
      {
         this.Name = "DefaultName";
         this.Age = 0;
         Console.WriteLine("Student is init...");
      }

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

而後在Program.cs中寫以下代碼:性能

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
   class Program
   {
      static void Main(string[] args)
      {
         Lazy<Student> stu = new Lazy<Student>();
         if(!stu.IsValueCreated)
            Console.WriteLine("Student isn't init!");
         Console.WriteLine(stu.Value.Name);
         stu.Value.Name = "Tom";
         stu.Value.Age = 21;
         Console.WriteLine(stu.Value.Name);
         Console.Read();
      }
   }
}

點擊F5,運行結果以下:優化

能夠看到,Student是在輸出Name屬性時才進行初始化的,也就是在第一次使用時才實例化,這樣就能夠減小沒必要要的開銷。this

Lazy<T> 對象初始化默認是線程安全的,在多線程環境下,第一個訪問 Lazy<T> 對象的 Value 屬性的線程將初始化 Lazy<T> 對象,之後訪問的線程都將使用第一次初始化的數據。spa

參考:http://msdn.microsoft.com/en-us/library/dd997286.aspx操作系統

相關文章
相關標籤/搜索