JVM原生不支持尾递归优化,但是Scala编译器支持

The JVM doesn’t support TCO natively, so tail recursive methods will need to rely on the Scala compiler performing the optimization.----------"Scala in Depth" 3.5.2

Jvm本身是不支持尾递归优化得,需要编译器支持,而Java编译器不支持,但是Scala支持。写一个简单的计算1到n的和的递归算法验证一下。


public class TestTailRecursion {

    private static long sum(long n, long total) {
        if (n <= 0) {
            return total;
        }
        return sum(n - 1, total + n);
    }

    public static void main(String[] args) {
        long sum = sum(100000, 0);
        System.out.println(sum);
    }
}

10w(可能每个机器不一样)的时候栈溢出。

object TestTailRecursion {

  def sum(n: Long, total: Long): Long = {
    if (n <= 0) total
    else sum(n - 1, total + n)
  }

  def main(args: Array[String]) {
    val total = sum(10000000, 0)
    println(total)
  }
}



Scala表示毫无压力。

可以讲Scala编译得到的bytecode用JavaDecompiler反编译,看到如下:

import scala.Predef.;
import scala.runtime.BoxesRunTime;

public final class TestTailRecursion$
{
  public static final  MODULE$;
  
  private TestTailRecursion$()
  {
    MODULE$ = this;
  }
  
  public long sum(long n, long total)
  {
    for (;;)
    {
      if (n <= 0L) {
        return 
          total;
      }
      total += n;n -= 1L;
    }
  }
  
  public void main(String[] args)
  {
    long total = sum(10000000L, 0L);
    Predef..MODULE$.println(BoxesRunTime.boxToLong(total));
  }
  
  static
  {
    new ();
  }
}




转载于:https://my.oschina.net/magicly007/blog/308210

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值