java基础---------递归和循环的使用效率

package java基础;

/**
* 参数递归和迭代的效率,递归效率太低,如果用到递归一般使用循环
*/

public class TestRecursion {
public static void main(String[] args) {
     //标记递归方法开始执行事件
long d1=System.currentTimeMillis();
System.out.printf("%d阶乘结果:%s%n",10,factorial(10));
      //递归程序结束时间
long d2=System.currentTimeMillis();
System.out.printf("递归耗时:%s%n",d2-d1);//计算出递归使用的时间
factorialLoop(10);
}

//计算阶乘方法,递归就是方法自己调用自己
static long factorial(int a){

if(a==1){
return 1;
}
else {
return a*factorial(a-1);
}
}
//高性能一般使用循环,递归效率太低
static long factorialLoop(int b){
long d3=System.currentTimeMillis();
long result=1;
while (b>1){
result*=b*(b-1);
b=b-2;
}
long d4=System.currentTimeMillis();
System.out.println("循环阶乘结果"+result);
System.out.printf("递归耗时:%s%n",d4-d3);
return result;

}
}

执行结果:

10阶乘结果:3628800
递归耗时:25
循环阶乘结果3628800
递归耗时:0


posted on 2019-05-19 08:45  zz测试笔记  阅读(1145)  评论(0编辑  收藏  举报