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

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

问题描述

Scala的一个方便功能是lazy val,其中val的求值被延迟到必要时(首次访问时).

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

lazy val的确切成本是什么-是否有与lazy val相关联的隐藏布尔标志来跟踪是否已对其进行评估,确切地进行了同步以及还有更多成本吗?

此外,假设我这样做:

class Something {
    lazy val (x, y) = { ... }
}

这与拥有两个单独的lazy val s xy一样吗?或者,对于一对(x, y),我只能获得一次开销吗?

解决方案

这取自

被编译为等同于以下Java代码的内容:

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

}

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

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.

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?

In addition, suppose I do this:

class Something {
    lazy val (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)?

解决方案

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

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天全站免登陆