Scala 的惰性 val 的(隐藏)成本是多少? [英] What's the (hidden) cost of Scala's lazy val?

查看:31
本文介绍了Scala 的惰性 val 的(隐藏)成本是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala 的一个方便的特性是 lazy val,其中对 val 的评估被延迟到有必要时(第一次访问).

One handy feature of Scala is lazy val, where the evaluation of a val is delayed until it's necessary (at first access).

当然,lazy val 必须有一些开销——Scala 必须在某处跟踪该值是否已经被评估并且评估必须同步,因为多个线程可能会尝试访问该值第一次同时.

Of course, a 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 的成本究竟是多少 - 是否有一个与 lazy val 相关联的隐藏布尔标志来跟踪它是否已被评估,是什么完全同步,是否还有其他费用?

What exactly is the cost of a 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 vals xy 是否相同,或者我是否只获得一次开销,对于这对(x, y)?

Is this the same as having two separate lazy vals x and y or do I get the overhead only once, for the pair (x, y)?

推荐答案

本文摘自 scala 邮件列表 并根据 Java 代码(而不是字节码)给出了 lazy 的实现细节:

This is taken from the scala mailing list and gives implementation details of lazy in terms of Java code (rather than bytecode):

class LazyTest {
  lazy val msg = "Lazy"
}

被编译为与以下 Java 代码等效的内容:

is compiled to something equivalent to the following Java code:

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;
  }

}

这篇关于Scala 的惰性 val 的(隐藏)成本是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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