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操作系统

相关文章
相关标签/搜索