Lazy initialization of an object means that its creation is delayed until its first use. (For this topic, the terms "lazy initialization" and "lazy" creation are synonymous.). Lazy initialization is mainly used to increase performance, prevent wasteful computing, and reduce program memory requirements. These are the most common scenarios:
If you have an object that is worth creating, and the program may not use it. For example, suppose you have a Customer object that has an Orders property that contains a large array of Order objects that require a database connection to initialize. If the user never asks to display Orders or use data in the calculation, then there is no reason to use system memory or computational cycles to create it. By using Lazy to declare an Orders object for lazy initialization, you can avoid losing system resources when the object is not in use.
If you have an object that is expensive and you want to postpone its creation until other costly operations are completed. For example, suppose your program loads several instances of an object when it starts, but only some of them are required immediately. You can increase the performance of the program by delaying the initialization of objects that are not required until the necessary objects are created.
Although you can write your own code to do lazy initialization, we recommend using Lazy instead. Lazy and its associated types also support thread safety and provide a consistent exception distribution policy.
Rakesh Kumar May 24 '11 at 1:24 pm 2011-05-24 13:24
source share