简体   繁体   English

Java中的尾部递归优化和递归

[英]Tail recursion optimization and recursion in Java

I have a question about tail calls optimization, I need to know how this java code behaves: 我有一个关于尾部调用优化的问题,我需要知道此Java代码的行为:

private void doSomething(int v) {

    inf f = someCalculation(v);

    if (f < 0) doSomething(v/2);
    else doSomething(v*2);

}

This code is a nonsense example but my question is, in such a case: 这段代码是一个废话示例,但在这种情况下,我的问题是:

  1. The first doSomething() call would be optimized? 第一个doSomething()调用会优化吗?
  2. The second doSomething() call would be optimized? 第二个doSomething()调用会优化吗?
  3. The if/else block affects in any way the optimization? if / else块是否以任何方式影响优化?

Thanks 谢谢

EDIT: 编辑:

Please provide an example on how you would do this if the language was not Java but something else that has TCO 请提供一个示例,说明如果该语言不是Java,而是其他具有TCO的语言,将如何执行此操作

Java 8 has no Tail Call Optimization whatsoever. Java 8完全没有尾调用优化。 No calls will be optimized (turned into iteration/goto statements). 没有调用将被优化(变成迭代/ goto语句)。

The discussion over TCO for Java has a long history, though, with Guy Steele being one of its best-known proponents. 但是,关于Java的TCO的讨论由来已久,而Guy Steele是其最著名的支持者之一。

I recommend reading this post from the mlvm-dev mailing list for a recent review of the subject. 我建议从mlvm-dev邮件列表中阅读此帖子 ,以mlvm-dev对该主题的最新评论。

Try running the following code: 尝试运行以下代码:

public static void main(String[] args) {
  for (int i = 1; i > 0; i *= 2) { doSomething(i); }
}

private static void doSomething(int start) {
  doSomething(start, start);
}

private static void doSomething(int i, int start) {
  if (i == 0) { System.out.println("done from " + start); }
  else { doSomething(i - 1, start); }
}

If the JVM can run it without stack overflow, then it should mean it can do tail recursion optimization (or a very good constant propagation). 如果JVM可以在没有堆栈溢出的情况下运行它,则意味着它可以进行尾部递归优化(或非常好的常数传播)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM