Java有懒惰的评估吗? [英] Does Java have lazy evaluation?

查看:87
本文介绍了Java有懒惰的评估吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Java在这种情况下有智能/懒惰评估:

I know that Java has smart/lazy evaluation in this case:

public boolean isTrue() {
    boolean a = false;
    boolean b = true;
    return b || (a && b); // (a && b) is not evaluated since b is true
}

但是怎么样:

public boolean isTrue() {
    boolean a = isATrue();
    boolean b = isBTrue();
    return b || a;
}

isATrue()调用即使 isBTrue()返回true?

Is isATrue() called even if isBTrue() returns true?

推荐答案

在Java中(和其他类C语言),这被称为 短路评估 *

In Java (and other C-like languages), this is referred to as short-circuit evaluation.*

是的,在第二个例子中 isATrue 总是被称为。也就是说,除非编译器/ JVM可以确定它没有可观察到的副作用,在这种情况下它可能会选择优化,但在这种情况下你无论如何都不会注意到差异。

And yes, in the second example isATrue is always called. That is, unless the compiler/JVM can determine that it has no observable side-effects, in which case it may choose to optimize, but in which case you wouldn't notice the difference anyway.



* 两者截然不同;前者本质上是一种优化技术,而第二种是由语言强制执行,可能影响可观察的程序行为。

我最初建议这是非常明显的来自懒惰的评价,但正如@Ingo在下面的评论中指出的那样,这是一个可疑的断言。人们可以将Java中的短路运算符视为惰性求值的一个非常有限的应用。

I originally suggested that this was quite distinct from lazy evaluation, but as @Ingo points out in comments below, that's a dubious assertion. One may view the short-circuit operators in Java as a very limited application of lazy evaluation.

然而,当函数式语言强制执行惰性求值语义时,它通常用于不同的原因,即防止无限(或至少,过度)递归。

However, when functional languages mandate lazy-evaluation semantics, it's usually for a quite different reason, namely prevention of infinite (or at least, excessive) recursion.

这篇关于Java有懒惰的评估吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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