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 java
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編譯獲得的bytecode用JavaDecompiler反編譯,看到以下: this
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 (); } }