C # Lazy for performance optimization <T> implement delayed Initialization
In. NET4.0, Lazy <T> can be used to implement delayed initialization of objects to optimize system performance. Delayed initialization delays object initialization until the first time this object is used. Delayed Initialization is a situation that we often encounter when writing a program. For example, it takes a lot of money to create an object, this object may not be used during system operation. In this case, you can use the delayed initialization function to initialize the object when it is used for the first time, if it is not used, Initialization is not required. In this way, the program efficiency is improved by using delayed initialization, so that the program consumes less memory. Next let's take a look at the code to create a console program. First, create a Student class. The Code is as follows: (because the English version of the operating system is used, the prompt is written in English. Please forgive me) copy the code 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 ;}} copy the code in Program. write the following code in cs: Copy the code 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 () ;}}you can see that Student is initialized only when the Name attribute is output, that is, it is instantiated only when used for the first time. This reduces unnecessary overhead. Lazy <T> object initialization is thread-safe by default. In a multi-threaded environment, the first thread that accesses the Value Attribute of the Lazy <T> object will initialize the Lazy <T> object, in the future, all accessed threads will use the data initialized for the first time.