尾部调用

在阮一峰大侠的ECMAScript 6 入门

了解到“尾递归”概念,拿到Java中一试吓一跳,对性能的提升不只是一星半点。

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);
    }

}
View Code

结果为:

传统:12586269025
传统耗时:30040
尾部:12586269025
尾部耗时:0

猜你喜欢

转载自www.cnblogs.com/g120/p/12208730.html