.net 什么是延迟初始化,它为什么有用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/978759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is lazy initialization and why is it useful?
提问by SNA
What is lazy initialization of objects? How do you do that and what are the advantages?
什么是对象的延迟初始化?你是怎么做到的,有什么好处?
回答by Bevan
Lazy Initialization is a performance optimization where you defer (potentially expensive) object creation until just before you actually need it.
延迟初始化是一种性能优化,您可以将(可能代价高昂的)对象创建推迟到您真正需要它之前。
One good example is to not create a database connection up front, but only just before you need to get data from the database.
一个很好的例子是不要预先创建数据库连接,而只是在需要从数据库中获取数据之前创建。
The key reason for doing this is that (often) you can avoid creating the object completely if you never need it.
这样做的关键原因是(通常)如果您不需要它,您可以完全避免创建对象。
回答by Michael
As others have mentioned, lazy initialization is delaying initialization until a component or object is used. You can view lazy initialization as a runtime applicationof the YAGNI principle- "You ain't gonna need it"
正如其他人所提到的,延迟初始化将初始化延迟到使用组件或对象。您可以查看延迟初始化为运行应用程序的YAGNI原则- “ You ain't gonna need it”
The advantages from an application perspective of lazy initialization are that users don't have to pay the initialization time for features they will not use. Suppose you were to initialize every component of your application up front. This could create a potentially long start time - users would have to wait dozens of seconds or minutes before your application is ready to use. They're waiting on and paying for initialization of features they may never use or not use right away.
从应用程序的角度来看,延迟初始化的优点是用户不必为他们不会使用的功能支付初始化时间。假设您要预先初始化应用程序的每个组件。这可能会造成潜在的较长启动时间 - 用户必须等待几十秒或几分钟才能使用您的应用程序。他们正在等待并为他们可能永远不会使用或不会立即使用的功能的初始化付费。
Instead, if you defer initializing those components until use time, your application will start up much quicker. The user will still have to pay the startup cost when using other components, but that cost will be amortized across the run of the program and not condensed into the beginning, and the user may associate the initialization time of these objects with the features they are using.
相反,如果您将这些组件的初始化推迟到使用时间,您的应用程序将启动得更快。用户在使用其他组件时仍需支付启动成本,但该成本将在程序运行期间分摊,不会压缩到开始时,用户可以将这些对象的初始化时间与它们的特性联系起来使用。
回答by Justin Niessner
Lazy Initialization is the concept of deferring object creation until the object is actually first used. If used properly, it can result in significant performance gains.
延迟初始化是将对象创建推迟到实际第一次使用该对象的概念。如果使用得当,它可以带来显着的性能提升。
Personally, I've used Lazy Initialization when creating my own hand-rolled ORM in .NET 2.0. When loading my collections from the database, the actual items in the collection were lazy initialized. This meant that the collections were created quickly, but each object was loaded only when I required it.
就个人而言,我在 .NET 2.0 中创建自己的手动 ORM 时使用了延迟初始化。从数据库加载我的集合时,集合中的实际项目被延迟初始化。这意味着集合可以快速创建,但每个对象仅在我需要时才加载。
If you're familiar with the Singleton pattern, you've probably seen lazy initialization in action as well.
如果您熟悉单例模式,您可能也看到了惰性初始化的作用。
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 instance of SomeClass is not initialized until it is first needed by the SomeClassSingleton consumer.
在这种情况下,SomeClass 的实例直到 SomeClassSingleton 消费者首次需要它时才会初始化。
回答by Dolphin
In general computing terms, 'lazy evaluation' means to defer the processing on something until you actually need it. The main idea being that you can sometimes avoid costly operations if you turn out to not need it, or if the value would change before you use it.
在一般的计算术语中,“懒惰评估”意味着推迟对某事的处理,直到您真正需要它。主要思想是,如果您证明不需要它,或者值在使用之前会发生变化,则有时可以避免昂贵的操作。
A simple example of this is System.Exception.StackTrace. This is a string property on an exception, but it isn't actually built until you access it. Internally it does something like:
一个简单的例子是 System.Exception.StackTrace。这是一个异常的字符串属性,但在您访问它之前它实际上并没有被构建。在内部,它执行以下操作:
String StackTrace{
get{
if(_stackTrace==null){
_stackTrace = buildStackTrace();
}
return _stackTrace;
}
}
This saves you the overhead of actually calling buildStackTrace until someone wants to see what it is.
这为您节省了实际调用 buildStackTrace 的开销,直到有人想要查看它是什么。
Properties are one way to simply provide this type of behavior.
属性是简单地提供此类行为的一种方式。
回答by Rakesh Kumar
Lazy initialization of an object means that its creation is deferred until it is first used. (For this topic, the terms lazy initialization and lazy instantiation are synonymous.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements. These are the most common scenarios:
对象的延迟初始化意味着它的创建被推迟到第一次使用。(对于本主题,延迟初始化和延迟实例化是同义词。)延迟初始化主要用于提高性能、避免浪费计算和减少程序内存需求。这些是最常见的场景:
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.
当您拥有一个创建成本很高的对象并且程序可能不会使用它时。例如,假设您在内存中有一个 Customer 对象,该对象具有一个 Orders 属性,该属性包含一个大型 Order 对象数组,要对其进行初始化,需要一个数据库连接。如果用户从不要求显示订单或在计算中使用数据,则没有理由使用系统内存或计算周期来创建它。通过使用 Lazy 声明 Orders 对象进行延迟初始化,可以避免在不使用该对象时浪费系统资源。
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.
当您有一个创建成本很高的对象,并且您希望将其创建推迟到其他昂贵的操作完成之后。例如,假设您的程序在启动时加载了多个对象实例,但只有其中一些是立即需要的。您可以通过将不需要的对象的初始化推迟到创建所需的对象来提高程序的启动性能。
Although you can write your own code to perform lazy initialization, we recommend that you use Lazy instead. Lazy and its related types also support thread-safety and provide a consistent exception propagation policy.
虽然您可以编写自己的代码来执行延迟初始化,但我们建议您改用 Lazy。Lazy 及其相关类型还支持线程安全并提供一致的异常传播策略。
回答by Karthik Krishna Baiju
//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
回答by Amir Rezaei
Here you can read about Lazy Initializationwith 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.
当您拥有一个创建成本很高的对象并且程序可能不会使用它时。例如,假设您在内存中有一个 Customer 对象,该对象具有一个 Orders 属性,该属性包含一个大型 Order 对象数组,要对其进行初始化,需要一个数据库连接。如果用户从不要求显示订单或在计算中使用数据,则没有理由使用系统内存或计算周期来创建它。通过使用 Lazy 声明 Orders 对象进行延迟初始化,可以避免在不使用该对象时浪费系统资源。
当您有一个创建成本很高的对象,并且您希望将其创建推迟到其他昂贵的操作完成之后。例如,假设您的程序在启动时加载了多个对象实例,但只有其中一些是立即需要的。您可以通过将不需要的对象的初始化推迟到创建所需的对象来提高程序的启动性能。
回答by Marc Charbonneau
The database examples that have been mentioned so far are good, but it's not restricted to just the data access layer. You could apply the same principles to any situation where performance or memory can be a concern. A good example (although not .NET) is in Cocoa, where you can wait until the user requests a window to actually load it (and its associated objects) from the nib. This can help keep memory usage down and speed up the initial application load, especially when you're talking about things like Preferences windows that won't be needed until some later time, if ever.
到目前为止提到的数据库示例都很好,但它不仅限于数据访问层。您可以将相同的原则应用于性能或内存可能成为问题的任何情况。一个很好的例子(虽然不是 .NET)是在 Cocoa 中,您可以在其中等待,直到用户请求一个窗口从 nib 实际加载它(及其关联的对象)。这可以帮助减少内存使用并加快初始应用程序加载速度,尤其是当您谈论诸如首选项窗口之类的事情时,如果有的话,直到稍后才会用到。
回答by BerggreenDK
As what I have understood about lazy init so far, is that the program does not load/request all data a once. It waits for the use of it before requesting it from eg. a SQL-server.
到目前为止,我对lazy init 的理解是,该程序不会一次加载/请求所有数据。它在从例如请求它之前等待它的使用。一个 SQL 服务器。
If you have a database with a large table joined with a large amount of subtables and you dont require the details joined from the other tabels unless going into "edit" or "view details", then Lazy Init. will help the application to go faster and first "lazy load" the detailsdata upon needed.
如果您有一个包含大量子表的大表的数据库,并且除非进入“编辑”或“查看详细信息”,否则您不需要从其他表中连接的详细信息,然后延迟初始化。将帮助应用程序运行得更快,并在需要时首先“延迟加载”详细信息。
In SQL or LINQ you can set this "setting" on your database model pr. dataelement.
在 SQL 或 LINQ 中,您可以在数据库模型 pr 上设置此“设置”。数据元素。
Hope this makes any sense to your question?
希望这对您的问题有意义吗?
A webclient (eg. a browser) does the same thing. The images are "lazy loaded" after the HTML and AJAX is also a "sort of lazy init" if used right.
网络客户端(例如浏览器)做同样的事情。图像在 HTML 之后是“延迟加载”的,如果使用得当,AJAX 也是一种“延迟 init”。

