递归与 For 循环 - 因子,Java [英] Recursion vs For loops - Factorials, Java

查看:42
本文介绍了递归与 For 循环 - 因子,Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种获取阶乘(循环与递归)的方法中哪一种更有效/更快?如果可以改进,如何改进?

Which of these two methods of getting a factorial (loop vs recursive) is more efficient/faster? and if that one can be improved, how so?

语言:Java

private static long factrecur(int n) {
    if (n == 0) {
        return 1;
    }
    else {
        return n * factrecur(n-1);
    }

}

private static long factloop(int a) {
    long total = 1;
    for (int b=a;b>=1;b--) {
        total *= b;
    }
    return total;
}

推荐答案

for 循环会更高效,因为没有方法调用的开销.(作为一般规则,循环几乎总是比递归更有效)

The for loop will be more efficient because there is no overhead of the method calls. (As a general rule loops are almost always more efficient than recursion)

解释为什么你必须深入了解调用方法时发生的事情的细节,以及称为 调用堆栈.

To explain why you have to get into the nitty gritty details of what happens when you call a method and something called the call stack.

基本上,当你调用一个方法时,它需要一些空间来处理(对于它的局部变量等)它也需要空间来传递给它的传入参数和一个地方来存储它的返回地址执行完成后应该去.这个空间是通过将值推送"到堆栈上来动态提供的.该堆栈空间一直被占用,直到方法返回,此时它被弹出".

Basically when you call a method it needs a bit of space to work with (for things like its local variables etc) it also needs space for the incoming parameters being passed to it and a place to store the return address of where it should go when it is done executing. This space is dynamically provided by 'pushing' the values on to a stack. That stack space remains occupied until the method returns at which point it is 'popped off'.

因此在这种情况下考虑递归:每次从自身内部调用方法时,您都会将更多数据推入堆栈,而不会从您所在的方法返回(因此不会释放调用方法占用的堆栈空间)).随着递归深入,内存量会增加.

So think about recursion in this context: every time you call the method from within itself you push more data onto the stack, without returning from the method you were in (and thus without freeing up the stack space the calling method was occupying). As your recursion goes deeper the amount of memory increases.

相比之下,您编写的 for 循环仅使用由一次堆栈帧推送提供的固定内存量.

In contrast the for loop you wrote just uses the fixed amount of memory provided by one stack frame push.

这篇关于递归与 For 循环 - 因子,Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆