When to lazy load?

后端 未结 8 1830
庸人自扰
庸人自扰 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:31

    A real lazy-loaded property for an int might look something like this:

    private int? _heavyLoadedInt;
    
    public int HeavyLoading
    {
        get
        {
            if (_heavyLoadedInt == null)
                _heavyLoadedInt = DoHeavyLoading();
            return _heavyLoadedInt.Value;
        }
    }
    

    Now if you look at this, you’ll see that there is some overhead here: You have to store the value in a nullable (extra memory); check it for null at every access, and retrieve the value from the nullable at every access.

    If your integer really requires some seriously heavy computation, then this construct makes sense. But new int() is not a heavy computation, it just returns 0. The overhead is tiny, but if you add this overhead to an even tinier operation (which is to read an integer), it makes no sense.

提交回复
热议问题