问题
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.
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...
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?
回答1:
Edit: I am now no longer sure what the advice is, so take my points below with a grain of salt when it comes to critiquing Twitter's advice. (But I give my own advice below.)
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.
来源:https://stackoverflow.com/questions/12959777/why-would-i-want-to-re-implement-lazy