Scala的懒惰val的(隐藏)成本是多少? [英] What's the (hidden) cost of Scala's lazy val?
问题描述
Scala的一个方便功能是lazy val
,其中val
的求值被延迟到必要时(首次访问时).
当然,lazy val
必须有一些开销-Scala必须跟踪某个值是否已经被求值并且求值必须同步,因为多个线程可能会在第一次尝试访问该值.同时.
lazy val
的确切成本是什么-是否有与lazy val
相关联的隐藏布尔标志来跟踪是否已对其进行评估,确切地进行了同步以及还有更多成本吗?>
此外,假设我这样做:
class Something {
lazy val (x, y) = { ... }
}
这与拥有两个单独的lazy val
s x
和y
一样吗?或者,对于一对(x, y)
,我只能获得一次开销吗?
这取自 被编译为等同于以下Java代码的内容: One handy feature of Scala is Of course, a What exactly is the cost of a In addition, suppose I do this: Is this the same as having two separate This is taken from the scala mailing list and gives implementation details of is compiled to something equivalent to the following Java code:
这篇关于Scala的懒惰val的(隐藏)成本是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!class LazyTest {
public int bitmap$0;
private String msg;
public String msg() {
if ((bitmap$0 & 1) == 0) {
synchronized (this) {
if ((bitmap$0 & 1) == 0) {
synchronized (this) {
msg = "Lazy";
}
}
bitmap$0 = bitmap$0 | 1;
}
}
return msg;
}
}
lazy val
, where the evaluation of a val
is delayed until it's necessary (at first access).lazy val
must have some overhead - somewhere Scala must keep track of whether the value has already been evaluated and the evaluation must be synchronized, because multiple threads might try to access the value for the first time at the same time.lazy val
- is there a hidden boolean flag associated with a lazy val
to keep track if it has been evaluated or not, what exactly is synchronized and are there any more costs?class Something {
lazy val (x, y) = { ... }
}
lazy val
s x
and y
or do I get the overhead only once, for the pair (x, y)
?lazy
in terms of Java code (rather than bytecode):class LazyTest {
lazy val msg = "Lazy"
}
class LazyTest {
public int bitmap$0;
private String msg;
public String msg() {
if ((bitmap$0 & 1) == 0) {
synchronized (this) {
if ((bitmap$0 & 1) == 0) {
synchronized (this) {
msg = "Lazy";
}
}
bitmap$0 = bitmap$0 | 1;
}
}
return msg;
}
}