本文介绍了何时懒加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我懒加载所有成员.我这样做已经有一段时间了,只是简单地考虑一下懒惰负担就可以了.

I lazy load all my members. I have been doing this for a while and simply taken lazy load to be a good thing at face value.

假设我们有

public class SomeClass
{
   public int anInt;
   public SomeReferenceType member1;

   public SomeClass()
   {
      //initialize members in constructor when needed (lazy load)
      anInt = new int();
      member1 = new SomeReferenceType();
   }
}

以这种方式做事有什么不利之处吗?这是适当的延迟加载模式吗?延迟加载值类型是否有意义(对于现代RAM来说,甚至有关系)吗?

Are there any disadvantages to doing things this way? Is this a proper lazy load pattern? Does it make sense to lazy load a value type (with modern RAM does it even matter)?


从您的回答中学到了什么之后,我想知道上面和这个之间是否有任何区别...


After what I have learned from your answers, I would like to know if there is any difference between the above and this...

public class SomeClass
    {
       public int anInt;
       public SomeReferenceType member1 = new SomeReferenceType();

       public SomeClass()
       {

       }
    }

推荐答案

首先,在构造函数内部初始化成员不是延迟加载.

First of all, initializing a member inside the constructor isn't lazy loading.

第一次请求时,延迟加载正在初始化成员. .NET中的一个简单示例(具有一些双重检查锁定,因此我们没有线程问题):

Lazy Loading is initializing the member the first time it is requested. A simple example in .NET (with some double-check locking so we don't have threading issues):

public class SomeClass
{
    private object _lockObj = new object();
    private SomeReferenceType _someProperty;

    public SomeReferenceType SomeProperty
    {
        get
        {
            if(_someProperty== null)
            {
                lock(_lockObj)
                {
                    if(_someProperty== null)
                    {
                        _someProperty= new SomeReferenceType();
                    }
                }
            }
            return _someProperty;
        }
        set { _someProperty = value; }
    }
}

幸运的是,如果您使用的是.NET 4,则现在可以使用 Lazy<T>为您处理问题,并使事情变得容易得多.

Luckily, if you're using .NET 4, you can now user the Lazy<T> Class which handles the issues for you and makes things a lot easier.

第二,当您有许多成员加载时可能花费很高,并且确定要使用所有这些值时,延迟加载是个好主意.这样的花费会使该类型的实例化变得不必要地缓慢.

Second of all, lazy loading is a good idea when you have many members that could be costly to load and you're sure that you're going to be using all of those values. That cost would cause the type to be un-necessarily slow to instantiate.

仅出于延迟加载的目的而进行的延迟加载会给您的代码增加不必要的复杂性,并且如果执行不当(例如,处理线程),可能会导致问题.

Lazy Loading just for the sake of lazy loading is adding unnecessary complexity to your code and could cause issues down the road if done improperly (when dealing with threading, for example).

这篇关于何时懒加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:18