递归版本与非递归版本的性能差异

    科技2022-07-14  122

    用递归版本与非递归版本实现了最最经典的阶乘,从而进行直观比较。

    public class test { public static long getFactorial1(long n) {//递归版本 if (n == 1) { return 1L; } return (long) n * getFactorial1(n - 1); } public static long getFactorial2(long n) {//非递归版本 long result = 1L; for (long i = 1; i <= n; i++) { result *= i; } return result; } public static void main(String[] args) { long n = 10000; long testTime = 10000; long start = System.currentTimeMillis(); for (long i = 0; i < testTime; i++) { getFactorial1(n); } long end = System.currentTimeMillis(); System.out.println("递归版本所耗费的时间:" + (end - start)); long start1 = System.currentTimeMillis(); for (long i = 0; i < testTime; i++) { getFactorial2(n); } long end1 = System.currentTimeMillis(); System.out.println("非递归版本所耗费的时间:" + (end1 - start1)); } }

    结果: 分析:主要是因为递归需要不断的往回走,直到找到递归的出口(n==1),而非递归版本则不需要进行这个操作。

    Processed: 0.016, SQL: 8