在阮一峰大侠的ECMAScript 6 入门
了解到“尾递归”概念,一旦使用递归,就最好使用尾递归,再也不用担心"栈溢出"(stack overflow)。
public class BeanInfoDemo { public static void main(String[] args) { Fibonacci(50); } private static void Fibonacci(int n) { long t1 = System.currentTimeMillis(); System.out.println("传统:" + FibonacciC(n)); long t2 = System.currentTimeMillis(); System.out.println("传统耗时:" + (t2 - t1)); System.out.println("尾部:" + FibonacciNew(n, 1, 1)); long t3 = System.currentTimeMillis(); System.out.println("尾部耗时:" + (t3 - t2)); } public static long FibonacciC(long n) { if (n <= 2) { return 1; } return FibonacciC(n - 1) + FibonacciC(n - 2); } public static long FibonacciNew(long n, long ac1, long ac2) { if (n <= 2) { return ac2; } return FibonacciNew(n - 1, ac2, ac1 + ac2); } }
结果为:
传统:12586269025 传统耗时:30040 尾部:12586269025 尾部耗时:0
参考:http://www.ruanyifeng.com/blog/2015/04/tail-call.html