performance lazy-initialization C# Lazy Loading

C# Lazy Loading

 

Foreword

Lazy loading the object loaded on demand actually create objects postponed until after the call to be created to initialize its delay (lazy loading) benefit is to improve system performance and avoid unnecessary calculation and unnecessary waste of resources.

Conventional these situations:

  • Objects created high costs and the program might not use it. For example, assume there are memory properties Orders having a Customer object, the object contains a large number of Order objects, these objects need to initialize a database connection. If the user is never required to display or use the data in the Orders calculation, there is no need to create it uses system memory or computing cycles. By using Lazy to declare the Orders object is used to slow initialize, the object can be avoided without using a waste of system resources.
  • Object creation cost, and you want to be postponed until after the other to create a high-cost operation is complete. For example, assume that a plurality of object instances program load at startup, but only part of loading immediately. By initializing unwanted objects postponed until create the required objects to enhance the program's startup performance. (Official sources)

Examples

Create a user class


 public class User
    {
        public string Name { get; set; } public int Age { get; set; } public User() { this.Name = "Name"; this.Age = 0; } } 

By default, Lazy objects are thread-safe. That is, if the constructor does not specify the type of security thread, Lazy objects This function creates a thread-safe. In multithreaded scenarios, the first thread to access the Value property of the object will be thread-safe Lazy for all subsequent access to its initialization on all threads, and all threads share the same data. Therefore, it does not matter which thread initializes the object, a race condition is benign.


    class Program
    {
        static void Main(string[] args) { Lazy<User> user = new Lazy<User>(); ThreadLocal<User> threadLocal = new ThreadLocal<User>(); if (!user.IsValueCreated) Console.WriteLine("The object is not initialized"); Console.WriteLine(user.Value.Name); user.Value.Name = "Name1"; user.Value.Age = 1; Console.WriteLine(user.Value.Name); Console.Read(); } } 
Thread safety objects LazyThreadSafetyMode mode parameters Boolean parameter isThreadSafe No thread safety parameters
Fully thread-safe; only one thread tries to initialize the value. ExecutionAndPublication true can.
Non-thread-safe. None false Not applicable.
Fully thread-safe; thread contention for initialization value. PublicationOnly Not applicable. Not applicable.

Which IsValueCreated property is a Boolean type, we can use this property to determine the current object has not been initialized

After the call, made creation

Let me say Lazy several constructors,

  • Lazy public (BOOL isThreadSafe) :
    isThreadSafe Boolean parameter, which parameter is used to specify whether the Value property is accessed from multiple threads. If you want to access the property from only one thread, the incoming false to obtain a modest performance advantage. If you want to access the property from multiple threads, the incoming true to indicate Lazy instance to correctly handle race condition (one thread throws an exception at initialization).

  • Lazy public (LazyThreadSafetyMode the MODE) : provides thread safety mode.

  • Lazy public (Func valueFactory) :
    the lambda expression is passed to the constructor new Lazy object. The next time access the Value property will cause initialization of the new Lazy and its Value property will thereafter return the new value has been assigned to the property.

to sum up

Reference: https://docs.microsoft.com/en-us/dotnet/framework/performance/lazy-initialization

Author: @ Feng Hui
Source: https://www.cnblogs.com/yyfh/p/11996509.html

Foreword

Lazy loading the object loaded on demand actually create objects postponed until after the call to be created to initialize its delay (lazy loading) benefit is to improve system performance and avoid unnecessary calculation and unnecessary waste of resources.

Conventional these situations:

  • Objects created high costs and the program might not use it. For example, assume there are memory properties Orders having a Customer object, the object contains a large number of Order objects, these objects need to initialize a database connection. If the user is never required to display or use the data in the Orders calculation, there is no need to create it uses system memory or computing cycles. By using Lazy to declare the Orders object is used to slow initialize, the object can be avoided without using a waste of system resources.
  • Object creation cost, and you want to be postponed until after the other to create a high-cost operation is complete. For example, assume that a plurality of object instances program load at startup, but only part of loading immediately. By initializing unwanted objects postponed until create the required objects to enhance the program's startup performance. (Official sources)

Examples

Create a user class


 public class User
    {
        public string Name { get; set; } public int Age { get; set; } public User() { this.Name = "Name"; this.Age = 0; } } 

By default, Lazy objects are thread-safe. That is, if the constructor does not specify the type of security thread, Lazy objects This function creates a thread-safe. In multithreaded scenarios, the first thread to access the Value property of the object will be thread-safe Lazy for all subsequent access to its initialization on all threads, and all threads share the same data. Therefore, it does not matter which thread initializes the object, a race condition is benign.


    class Program
    {
        static void Main(string[] args) { Lazy<User> user = new Lazy<User>(); ThreadLocal<User> threadLocal = new ThreadLocal<User>(); if (!user.IsValueCreated) Console.WriteLine("The object is not initialized"); Console.WriteLine(user.Value.Name); user.Value.Name = "Name1"; user.Value.Age = 1; Console.WriteLine(user.Value.Name); Console.Read(); } } 
Thread safety objects LazyThreadSafetyMode mode parameters Boolean parameter isThreadSafe No thread safety parameters
Fully thread-safe; only one thread tries to initialize the value. ExecutionAndPublication true can.
Non-thread-safe. None false Not applicable.
Fully thread-safe; thread contention for initialization value. PublicationOnly Not applicable. Not applicable.

Which IsValueCreated property is a Boolean type, we can use this property to determine the current object has not been initialized

After the call, made creation

Let me say Lazy several constructors,

  • public Lazy (bool isThreadSafe)
    isThreadSafe 的布尔参数,该方法参数用于指定是否从多线程访问 Value 属性。 如果想要仅从一个线程访问属性,则传入 false 以获取适度的性能优势。 如果想要从多线程访问属性,则传入 true 以指示 Lazy 实例正确处理争用条件(初始化时一个线程引发异常)。

  • public Lazy (LazyThreadSafetyMode mode):提供线程安全模式。

  • public Lazy (Func valueFactory)
    lambda 表达式传递给新的 Lazy 对象的构造函数。 下一次访问 Value 属性将导致新 Lazy 的初始化,并且其 Value 属性此后会返回已分配给该属性的新值。

总结

参考:https://docs.microsoft.com/en-us/dotnet/framework/performance/lazy-initialization

作者:@冯辉
出处:https://www.cnblogs.com/yyfh/p/11996509.html

Guess you like

Origin www.cnblogs.com/Leo_wl/p/12315368.html