JVM究竟有没有对尾递归进行优化?
看了好几篇博文,说没有,便在JDK8下做了个测试。
package fibonicc;
public class Test {
//1 1 2 3 5 8
private static int fibonicc(int n) {
if(n<=1) {
return 1;
}
return fibonicc(n-1)+fibonicc(n-2);
}
//n递减 代表一直运算到n=1为止
private static int fibonicc2(int n,int last,int total) {
if(n==1) {
return total;
}
return fibonicc2(n-1,total,last+total);
}
//尾递归 还是没有 循环快
private static int fibonicc3(int n) {
if(n<=1) {
return 1;
}
int last = 1;
int current = 1;
int i=2;
int tmp = current;
while(i++<=n) {
tmp = current;
current = last+current;
last = tmp;
}
return current;
}
private static int fibonicc4(int n,int last,int total) {
if(n==1) {
return total;
}
int result = fibonicc4(n-1,total,last+total);
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// System.out.println(fibonicc(50));
long start = (System.nanoTime());
System.out.println(fibonicc2(5000,1,1));
System.out.println(System.nanoTime()-start);
start = (System.nanoTime());
System.out.println(fibonicc3(5000));
System.out.println(System.nanoTime()-start);
start = (System.nanoTime());
System.out.println(fibonicc4(5000,1,1));
System.out.println(System.nanoTime()-start);
}
}
fibonicc是普通递归,很慢。
fibonicc2是尾递归实现,fibonicc2(5000,1,1)耗时1092785纳秒,比普通递归快。
fibonicc3是循环实现,fibonicc3(5000)耗时419347纳秒,比尾递归快。
fibonicc4是同fobonicc2的时间复杂度一致的非尾调,耗时1132819,看来和尾递归耗时差不多。
网友评论