递归的写法不同,效率不同
public class RecursionMain {
private static long time = 0L;
public static void main(String[] args) {
time = System.nanoTime();
System.out.println(RecursionTest.recursion1(10_000));
System.out.println((System.nanoTime() - time) / 1000_000);
time = System.nanoTime();
System.out.println(RecursionTest.recursion2(1,10_000));
System.out.println((System.nanoTime() - time) / 1000_000);
}
/**
* 递归的 省时 费时
*/
private static class RecursionTest {
/**
* 使用栈帧方式的阶乘
* @param n 数
* @return 值
*/
static long recursion1(long n) {
return n == 1 ? 1 : n + recursion1(n - 1);
}
/**
* 阶乘的尾递定义
* @param acc 值
* @param n 数
* @return 值
*/
static long recursion2(long acc, long n) {
return n == 1 ? acc : recursion2(acc + n, n - 1);
}
}
}
在4核电脑上运行:
结果:
50005000
3
50005000
0