What is lazy initialization and why is it useful?

前端 未结 9 1181
小鲜肉
小鲜肉 2020-12-12 12:40

What is lazy initialization of objects? How do you do that and what are the advantages?

9条回答
  •  情深已故
    2020-12-12 12:48

    Here you can read about Lazy Initialization with sample code.

    • When you have an object that is expensive to create, and the program might not use it. For example, assume that you have in memory a Customer object that has an Orders property that contains a large array of Order objects that, to be initialized, requires a database connection. If the user never asks to display the Orders or use the data in a computation, then there is no reason to use system memory or computing cycles to create it. By using Lazy to declare the Orders object for lazy initialization, you can avoid wasting system resources when the object is not used.

    • When you have an object that is expensive to create, and you want to defer its creation until after other expensive operations have been completed. For example, assume that your program loads several object instances when it starts, but only some of them are required immediately. You can improve the startup performance of the program by deferring initialization of the objects that are not required until the required objects have been created.

提交回复
热议问题