1. Overview
It takes a lot of consumption to create an object, and this object may not be used during the run, so in order to avoid creating the object every time, lazy initialization (also called lazy instantiation) comes into play.
Delayed initialization occurs in . NET 4.0, which is primarily used to improve performance, avoid wasted computation, and reduce program memory requirements. It can also be called on-demand loading.
2. Basic grammar
3. Implement with examples
Start by creating a Student class with the following code:
Create a console program with the following code:
After setting the breakpoint for debugging, I found that after new, the value of Student's IsValueCreated was false and the value of value was null
Then, when calling the Name property, the value of student's IsValueCreated is true, and the value of value is no longer null
Run result:
It can be seen that the Student is initialized only when the Name attribute is output, that is, it is initialized when it is used for the first time, so as to achieve the purpose of reducing consumption.
This example is simple and the <T>most basic way to use Lazy. We can also use<T> Lazy's overload function, Lazy<T> (Func<T>), to pass in a delegate with a return value to set the property value of the lazy initialization object.
Run result:
Note: Lazy<T> object initialization is thread-safe by default, and in a multi-threaded environment, the first thread to access<T> the Lazy object's Value property will initialize the Lazy<T> object, and subsequent access threads will use the data initialized for the first time.
4. Application scenarios
There is an object that has a lot of overhead to create, and the program may not use it. For example, suppose your program loads several instances of objects at startup, but only a few instances need to be executed immediately. You can improve the startup performance of your program by delaying the initialization of unnecessary objects until after the necessary objects have been created.
|