Java 中的尾调用优化
Tail Call Optimisation in Java
自 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支持Tail-Call Optimisation。 Scala 在编译时进行尾递归优化。为什么不能 Java 使用相同的方法?
PS:不确定Java的最新版本(Java 11 as now)现在是否有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.
据我所知,尾调用的工作尚未开始,因为纤程和延续目前似乎具有更高的优先级。
我在这里读了一篇非常好的博客 post 关于如何在 Java 中实现尾递归:
Knoldus blog post on Java tail recursion
但是,他们博客上的代码无法编译,所以我用他们的代码创建了一个小型存储库,但修复了语法,因此可以编译。
Github repo with working code
希望这对某人有用,我发现 Knoldus 博客 post 上提出的想法非常有趣。
编辑:实际上我后来发现博客 post 中提出的想法最初是 Venkat Subramaniam 的。他在演讲中讨论了这些主题 here。
自 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支持Tail-Call Optimisation。 Scala 在编译时进行尾递归优化。为什么不能 Java 使用相同的方法?
PS:不确定Java的最新版本(Java 11 as now)现在是否有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.
据我所知,尾调用的工作尚未开始,因为纤程和延续目前似乎具有更高的优先级。
我在这里读了一篇非常好的博客 post 关于如何在 Java 中实现尾递归: Knoldus blog post on Java tail recursion
但是,他们博客上的代码无法编译,所以我用他们的代码创建了一个小型存储库,但修复了语法,因此可以编译。 Github repo with working code
希望这对某人有用,我发现 Knoldus 博客 post 上提出的想法非常有趣。
编辑:实际上我后来发现博客 post 中提出的想法最初是 Venkat Subramaniam 的。他在演讲中讨论了这些主题 here。