Lazy T?的缺点 [英] Disadvantages of Lazy<T>?

查看:114
本文介绍了Lazy T?的缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始在整个应用程序中使用 Lazy ,想知道使用Lazy<T>时是否需要考虑任何明显的负面影响?

I recently started using Lazy throughout my application, and I was wondering if there are any obvious negative aspects that I need to take into account when using Lazy<T>?

我正在尝试尽可能多地利用Lazy<T>,主要是为了减少已加载但不活动的插件的内存占用.

I am trying to utilize Lazy<T> as often as I deem it appropriate, primarily to help reduce the memory footprint of our loaded, but inactive plugins.

推荐答案

我将在我的评论中扩大一点,内容为:

I'll expand a bit on my comment, which reads:

我刚刚开始使用Lazy,发现它通常是指示性的 设计不良或程序员的懒惰.还有一个 缺点是您必须提高警惕 变量,并创建适当的闭包.

I've just started using Lazy, and find that it's often indicative of bad design; or laziness on the part of the programmer. Also, one disadvantage is that you have to be more vigilant with scoped up variables, and create proper closures.

例如,我使用Lazy<T>来创建用户可以在我的( sessionless )MVC应用程序中看到的页面.这是一个向导向导,因此用户可能希望转到随机的上一步步骤.进行握手时,将创建一个Lazy<Page>对象数组,如果用户指定作为步骤,则将评估该确切页面.我发现它提供了良好的性能,但是我不喜欢它的某些方面,例如,许多我的foreach构造现在看起来像这样:

For example, I've used Lazy<T> to create the pages the user can see in my (sessionless) MVC app. It's a guiding wizard, so the user might want to go to a random previous step. When the handshake is made, an array of Lazy<Page> objects is crated, and if the user specifies as step, that exact page is evaluated. I find it delivers good performance, but there are some aspects to it that I don't like, for example many of my foreach constructs now look like this:

foreach(var something in somethings){
     var somethingClosure = something;
     list.Add(new Lazy<Page>(() => new Page(somethingClosure));
} 

即您必须非常主动地处理关闭问题.否则,我认为存储lambda并在需要时对其进行评估不会对性能造成太大影响.

I.e. you have to deal with the problem of closures very proactively. Otherwise I don't think it's such a bad performance hit to store a lambda and evaluate it when needed.

另一方面,这可能表明程序员正在使用Lazy<Programmer>,从某种意义上说,您宁愿现在不考虑程序,而是在需要时让适当的逻辑进行评估,例如我的情况-无需构建该数组,我只需弄清楚该特定请求的页面是什么即可;但是我选择了懒惰,并全力以赴.

On the other hand this might be indicative that the programmer is being a Lazy<Programmer>, in the sense that you'd prefer not thinking through your program now, and instead let the proper logic evaluate when needed, as with example in my case - instead of building that array, I could just figure out just what that specific requested page would be; but I chose to be lazy, and do an all in approach.

编辑

在我看来,Lazy<T>在使用并发时也有一些特殊之处.例如,对于某些情况,有一个ThreadLocal<T>,对于特定的多线程情况有一些标志配置.您可以在 msdn 上阅读更多内容.

It occurs to me that Lazy<T> also has a few peculiars when working with concurrency. For example there's a ThreadLocal<T> for some scenarios, and several flag configurations for your particular multi-threaded scenario. You can read more on msdn.

这篇关于Lazy T?的缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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