What is lazy initialization and why is it useful?

What is lazy initialization of objects? How do you do it and what are the benefits?

+69
Jun 11 '09 at 0:23
source share
9 answers

Lazy Initialization is a performance optimization when you delay the (potentially expensive) creation of an object before you really need it.

A good example is not creating a database connection in front, but just before you need to get data from the database.

The key reason for this is that (often) you can completely not create an object if you never need it.

+89
Jun 11 '09 at 0:25
source share

As others have noted, lazy initialization delays initialization until a component or object is used. You can view lazy initialization as a runtime application of the YAGNI principle - “You won’t need it”

The advantages from the point of view of the lazy initialization application are that users do not need to pay initialization time for functions that they will not use. Suppose you were to initialize each component of your application in front. This can create a potentially long start time - users will have to wait a few tens of seconds or minutes before your application is ready to use. They wait and pay for the initialization of functions that they can never use or never use immediately.

Instead, if you delay the initialization of these components until you use them, your application will launch much faster. The user will still have to pay the launch cost when using other components, but this cost will be amortized over the entire time of the program and not configured at the beginning, and the user can associate the initialization time of these objects with the functions that they use.

+42
Jun 11 '09 at 0:46
source share

Lazy Initialization is the concept of deferred object creation until the object is used first. Used properly, this can lead to a significant increase in performance.

Personally, I used Lazy Initialization when creating my own hand-crafted ORM in .NET 2.0. When loading my collections from the database, the actual elements of the collection were initialized lazy. This meant that collections were created quickly, but each object was loaded only when I required it.

If you are familiar with the Singleton pattern, you probably saw lazy initialization in action.

public class SomeClassSingleton { private static SomeClass _instance = null; private SomeClassSingleton() { } public static SomeClass GetInstance() { if(_instance == null) _instance = new SomeClassSingleton(); return _instance; } } 

In this case, the SomeClass instance is not initialized until the first consumer of SomeClassSingleton needs it.

+14
Jun 11 '09 at 0:41
source share

In general computational terms, “lazy evaluation” means delaying processing on something until you actually need it. The basic idea is that sometimes you can avoid costly operations if you do not need it or if the value changes before using it.

A simple example of this is System.Exception.StackTrace. This is a string property for exception, but it is not actually created until you access it. Inside, he does something like:

 String StackTrace{ get{ if(_stackTrace==null){ _stackTrace = buildStackTrace(); } return _stackTrace; } } 

This will save you the overhead of calling callStackTrace until someone wants to see what it is.

Properties is one way to simply provide this type of behavior.

+5
Jun 11 '09 at 0:45
source share

Here you can read the Lazy Initialization with sample code.

  • If you have an object that is expensive to create, and the program may not use it. For example, suppose you have a client object in memory that has the Orders property that contains a large array of order objects that need to be initialized, requires a database connection. If the user never asks to display Orders or use data in the calculation, then there is no reason to use a memory system or computational cycles to create This. By using Lazy to declare an Orders object for lazy initialization, you can avoid wasting system resources when the object is not in use.

  • If you have an object that is expensive to create, and you want to postpone your creation until other expensive operations are completed. For example, suppose your program loads several objects when it starts, but only some of them are required immediately. You can improve startup program execution to delay initialization of objects that are not required until the required objects have been created.

+2
Nov 05 2018-10-11T00:
source share

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.

+2
May 24 '11 at 1:24 pm
source share
 //Lazy instantiation delays certain tasks. //It typically improves the startup time of a C# application. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LazyLoad { class Program { static void Main(string[] args) { Lazy<MyClass> MyLazyClass = new Lazy<MyClass>(); // create lazy class Console.WriteLine("IsValueCreated = {0}",MyLazyClass.IsValueCreated); // print value to check if initialization is over MyClass sample = MyLazyClass.Value; // real value Creation Time Console.WriteLine("Length = {0}", sample.Length); // print array length Console.WriteLine("IsValueCreated = {0}", MyLazyClass.IsValueCreated); // print value to check if initialization is over Console.ReadLine(); } } class MyClass { int[] array; public MyClass() { array = new int[10]; } public int Length { get { return this.array.Length; } } } } // out put // IsValueCreated = False // Length = 10 // IsValueCreated = True 
+2
Jan 05
source share

As far as I understand about lazy init so far, the fact is that the program does not load / request all the data a once. He is waiting for his use before requesting it, for example. SQL server.

If you have a database with a large table, combined with a large number of subtitles, and you do not need details connected to other tabs, unless you go to "edit" or "view details", then "Lazy Init". help the application accelerate and first "lazy load" on the necessary details.

In SQL or LINQ, you can set this “setting” in your pr database model. dataelement.

Hope this makes sense for your question?

A web client (such as a browser) does the same. Images are “lazy loaded” after HTML, and AJAX is also a “kind of lazy init” when used properly.

+1
Jun 11 '09 at 0:29
source share

The examples of databases that have been mentioned so far are good, but not limited to the level of data access. You can apply the same principles in any situation where performance or memory can be troubling. A good example (though not .NET) is in Cocoa, where you can wait until the user asks the window to actually load it (and its related objects) from nib. This can help reduce memory usage and speed up the loading of the original application, especially when you talk about things like settings windows that you won’t need until later, if ever.

+1
Jun 11 '09 at 0:44
source share



All Articles