When to lazy load?

后端 未结 8 1879
庸人自扰
庸人自扰 2020-12-31 17:14

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.

Let\'s say we have

publi         


        
8条回答
  •  庸人自扰
    2020-12-31 17:40

    That's not really a lazy load. That's initializing on construction. Typically what we mean in lazy loading is to construct the item the first time it's referenced.

        private string _someField;
    
        public string SomeField
        {
            get 
            {
                // we'd also want to do synchronization if multi-threading.
                if (_someField == null)
                {
                    _someField = new String('-', 1000000);
                }
    
                return _someField;
            }
        }
    

    It used to be one of the typical ways to Lazy load was a check,lock,check so that you don't lock if it's already created, but since it's possible for two items to pass the check and wait for the lock, you check again in the lock:

    public class SomeClass
    {
        private string _someField;
    
        private readonly object _lazyLock = new object();
    
    
        public string SomeField
        {
            get 
            {
                // we'd also want to do synchronization if multi-threading.
                if (_someField == null)
                {
                    lock (_lazyLock)
                    {
                        if (_someField == null)
                        {
                            _someField = new String('-', 1000000);
                        }
                    }
                }
    
                return _someField;
            }
        }
    }
    

    There are various ways to do this, in fact in .NET 4.0, there is a Lazy type that can help you do thread-safe lazy-loading easily.

    public class SomeClass
    {
        private readonly Lazy _someField = new Lazy(() => new string('-', 10000000), true);
    
        private readonly object _lazyLock = new object();
    
    
        public string SomeField
        {
            get
            {
                return _someField.Value;
            }
        }
    }
    

    As to the why, typically lazy-loading is a good scheme if the object you are creating tends to be expensive (memory or time) and there's no guarantee you'll need it. If you are reasonably sure it will always be used, then you should just construct it outright.

提交回复
热议问题