java - Java 中的尾调用优化

标签 java recursion compilation jvm tail-recursion

从 Java 8 开始,Java 不提供尾调用优化 (TCO)。 在研究它时,我开始知道 reason这是:

In JDK classes [...] there are a number of security sensitive methods that rely on counting stack frames between JDK library code and calling code to figure out who's calling them.

然而,基于 JVM 的 Scala 支持尾调用优化。 Scala 在编译时进行尾递归优化。为什么 Java 不能使用相同的方法?

PS:不确定 Java 的最新版本(目前为 Java 11)是否具有 TCO。如果知道的人也可以分享一下,那就太好了。

注意事项:

  1. 我知道 TCO 处于积压状态并且优先级较低,但想知道为什么 Java 不能像 Scala 一样在编译时进行更改。

  2. Java 没有尾调用优化,原因与大多数命令式语言没有尾调用优化的原因相同。命令式循环是该语言的首选风格,程序员可以用命令式循环代替尾递归。 ( Source )

最佳答案

Why can't Java use the same approach ?

我不能说将使用哪种方法,但在 Project Loom's proposal 中有更好的解释:

As adding the ability to manipulate call stacks to the JVM will undoubtedly be required, it is also the goal of this project to add an even lighter-weight construct that will allow unwinding the stack to some point and then invoke a method with given arguments (basically, a generalization of efficient tail-calls). We will call that feature unwind-and-invoke, or UAI. It is not the goal of this project to add an automatic tail-call optimization to the JVM.

据我所知,尾部调用的工作尚未开始,因为纤维和延续目前似乎具有更高的优先级。

关于java - Java 中的尾调用优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53354898/

相关文章:

java - 使用 json 节点解析 JSon 字符串

java - 在 selector.select() 中检测 ServerSocketChannel 何时关闭

java - 如何检查数据库的分支中是否存在子项,以便我可以根据该子项返回值

c++ - 找到数字数组的所有可能的解释

swift - Xcode 7 编译错误 : "Command failed due to signal: Segmentation fault: 11"

java - Android 可绘制范例!

javascript - 从自然数翻转 0's and 1' s

python - Python 中的递归回溯——在秤上平衡重量

clojure - 为什么 Clojure 在 AOT 编译期间评估表单?

c - 链接器是否查找头文件