为什么我要重新实现懒惰? [英] Why would I want to re-implement lazy?

查看:44
本文介绍了为什么我要重新实现懒惰?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Twitter 的 Effective Scala 页面上阅读关于 Lazyness [原文如此] 的部分包括这个建议(重点是我的):

I was reading the section on Lazyness [sic] over at Twitter's Effective Scala page, which includes this suggestion (emphasis is mine):

为此目的使用惰性字段[按需计算和缓存值],但在语义要求惰性时避免使用惰性.在这些情况下最好是明确的,因为它使成本模型明确,并且可以更精确地控制副作用.

Use lazy fields for this purpose [computing and caching values on-demand], but avoid using lazyness when lazyness is required by semantics. In these cases it's better to be explicit since it makes the cost model explicit, and side effects can be controlled more precisely.

我不明白他们为什么会提出这个要求.为什么在语义需要惰性的情况下最好避免使用 lazy 关键字(意味着它是程序正确性所必需的,而不仅仅是将其用作优化).我看不出编写自己的惰性初始化代码如何使 惰性 比使用语言中内置的 lazy 关键字更清楚这一事实!我知道使 lazy 字段成为线程安全会涉及一些额外的开销,但我认为这不是他们在这里得到的......

I don't understand why they would make this claim. Why would it be better to avoid using the lazy keyword for cases when laziness is required by the semantics (meaning that it's necessary for correctness in your program rather than just using it as an optimization). I don't see how writing your own lazy initialization code would make the fact that laziness is required more clear than using the lazy keyword built into the language! I know there's a bit of extra overhead involved with making lazy fields thread-safe, but I don't think that's what they're getting at here...

这个关于使用 lazy 的指南是否有一些我完全遗漏的隐藏优点,或者我最好忽略这个建议?

Is there some hidden merit to this guideline on the use of lazy that I'm totally missing, or am I better off just ignoring this suggestion?

推荐答案

我现在不再确定建议 是什么,所以请保留下面我的观点当谈到批评 Twitter 的建议时.(但我在下面给出了自己的建议.)

我也不同意这些建议,但我(过去)认为他们的观点是懒惰太容易了.您为访问惰性值付出了性能损失,但在使用点您没有注意到除了访问正常值之外您正在做任何事情.当然,这是使惰性 val 如此有用的一件事:您可以在惰性行为之间切换,并且根本不更改您的界面.但是,如果人们用 lazy 随机填充他们的代码,关键区域的性能可能会受到影响(假设它不超过惰性求值所弥补的),初始化的顺序将更难预测(尤其是如果您正在执行很多副作用,这很重要),等等.

I also disagree with the advice, but I (used to) think their point is that laziness is too easy. You pay a performance penalty for accessing a lazy value, but you don't notice at the use-point that you are doing anything aside from accessing a normal val. Of course, that's one thing that makes lazy vals so useful: you can switch between lazy behavior and not and not change your interface at all. But if people pepper their code randomly with lazy, performance in critical regions will likely suffer (assuming that it is not more than made up for by lazy evaluation), order of initialization will be harder to predict (especially important if you're performing a lot of side-effects), and so on.

即便如此,我认为露骨更糟糕,但你必须遵守纪律.如果您不能指望文档或纪律,也许最好完全避免它.

Even so, I think it is worse to be explicit but you do have to be disciplined. If you cannot count on either documentation or discipline, maybe it's better to just avoid it entirely.

这篇关于为什么我要重新实现懒惰?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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