从 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。如果知道的人也可以分享一下,那就太好了。
注意事项:
我知道 TCO 处于积压状态并且优先级较低,但想知道为什么 Java 不能像 Scala 一样在编译时进行更改。
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/