延迟加载 - 最好的方法是什么? [英] Lazy loading - what's the best approach?

查看:27
本文介绍了延迟加载 - 最好的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过很多延迟加载的例子——你的选择是什么?

I have seen numerous examples of lazy loading - what's your choice?

给定一个模型类,例如:

Given a model class for example:

public class Person
{
    private IList<Child> _children;
    public IList<Child> Children
    {
        get {
            if (_children == null)
                LoadChildren();
            return _children;
        }
    }
}

Person 类不应该知道它的子类是如何加载的......或者应该知道吗?它肯定应该控制何时填充属性?

The Person class should not know anything about how it's children are loaded .... or should it? Surely it should control when properties are populated, or not?

您是否有一个将 Person 与其子集合耦合在一起的存储库,或者您是否会使用不同的方法,例如使用 lazyload 类 - 即便如此,我也不希望我的模型架构中的延迟加载类模糊.

Would you have a repository that couples a Person together with its children collection or would you use a different approach, such as using a lazyload class - even then, I don't want a lazyload class blurring in my model architecture.

如果首先请求一个 Person 然后它的子项(即在这种情况下不是延迟加载)或以某种方式延迟加载,您将如何处理性能.

How would you handle performance if first requesting a Person and then its Children (i.e. not lazy loading in this instance) or somehow lazy loading.

这一切都归结为个人选择吗?

Does all this boil down to personal choice?

推荐答案

最好的延迟加载是避免它 ;) 线程安全是您必须立即处理的问题.我不知道我有多少次看到具有 8 个 cpu 内核的生产系统为 每个使用中的 延迟加载模式运行 8 次延迟加载.至少在服务器启动时,所有服务器核心都趋向于在同一个地方结束.

The best lazy loading is avoiding it ;) Thread safety is an immediate problem you'll have to handle. I have no count of how often I have seen production systems with 8 cpu cores run lazy loading 8 times for every single lazy loading pattern in use. At least on server startups all server cores have a tendency to end up in the same places.

如果可以,让 DI 框架为您构建它.如果你不能,我仍然更喜欢显式构造.所以各种AOP魔法干脆别跟我扯了,去类外的显式构造.不要把它放在person类中,只要做一个以正确方式构造对象的服务即可.

Let a DI framework construct it for you instead, if you can. And if you cannot, I still prefer explicit construction. So all sorts of AOP magic simply do not cut it with me, go for explicit construction outside the class. Don't put it inside the person class, just make a service that constructs the objects in the proper manner.

引入或多或少透明地做这些事情的魔法"层看起来是个好主意,但我还没有遇到没有不可预见和有问题的后果的实现.

Introducing "magic" layers that more or less transparently do these things seem like a nice idea, but I have yet to come across implementations that do not have unforseen and problematic consequences.

这篇关于延迟加载 - 最好的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆