Business Scenario:
In project development, we often encounter loading problems with specific objects, and some instance objects are not required to be used after they are created, but are called according to the business scenario, so many invalid instances can be loaded
Deferred initialization occurs in. NET 4.0, which is used primarily to improve performance, avoid wasted computing, and reduce program memory requirements. can also be called, load on demand
code example:
1. Non-deferred load condition
A. Create student class:
View Code
B. Procedure entry:
View Code
C. Running results:
D. Results note:
The program run directly calls the constructor, before using the student object
2. Using Lazy Loading
A. Create Student class: (Code above 1)
B. Procedure entry:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedemo_lazy_{classProgram {/// <summary> ///Program Entry/// </summary> /// <param name= "args" ></param> Static voidMain (string[] args) {Lazy<Student> Student =NewLazy<student>(); Console.WriteLine ("An instance object has been created"); Console.WriteLine ("does the student age show? (0 No 1 Yes)"); stringID =Console.ReadLine (); if(id = ="1") {Console.WriteLine (student. Value.age); } console.readline (); } }}
View Code
C. Running results:
First enter 0 results, the result is: The student object has been created, but not instantiated, because the business is not used
Run again, enter 1, result description: Student object has been created, call object Instantiation method
Case Summary:
In the case of business function development, if there is a high cost of object creation, rather than the need to immediately use it, as in the above example, depending on the interface input whether to display the student age, to dynamically decide whether to instantiate the student object, if the program starts in the object is required to use immediately, do not recommend the use of lazy loading, Immediate loading will improve the efficiency of program startup;
Note:
lazy is thread-safe by default, and when multiple threads are running concurrently, the initialization of an object is only performed by the first thread invocation, and subsequent thread invocation execution does not create/Invoke the object instance more than once
. NET on-demand load/lazy load lazy<t>