为什么以递归方式调用函数很糟糕? [英] Why is it bad to call functions recursively?

查看:67
本文介绍了为什么以递归方式调用函数很糟糕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我上的课中,我的老师不鼓励学生递归调用函数.例如,如果要在以下代码中调用main函数:

  if(x> 5){printf(您的电话号码太大.请输入小于5的电话号码.");主要的();} 

我被鼓励使用:

  int x;而(x> 5){printf("\ n您的号码太高.请输入小于5的数字.");scanf(%d",& x);} 

虽然我知道while函数是解决此特定问题的更简单方法,但我们被告知要避免整个递归,尤其是对于main()而言.但是,我认为这是编程中使用的相当重要的概念.为什么应该避免这种事情,尤其是在调用main()时?

解决方案

好问题.

有些类型的问题可以通过递归更轻松地解决,但是通常,只要有可能,通常迭代效率更高.

简而言之,这样做的原因是,每次进入新函数时,我们都必须保存上次中断的位置以及所有在那里的变量,以便当内部函数终止时,我们可以在父母中恢复.

最终,您将必须记住每个父函数的数据,这会很多,因此您将耗尽内存.同样,保存数据和创建新上下文以执行新功能的过程也需要花费少量时间,而当您执行数十万次调用时,这些时间会加起来.

通过阅读有关计算机体系结构和汇编语言的信息,您可以了解有关编译器为使我们视为理所当然的所有事物(功能,循环)所做的各种有趣的事情.

例如,查看有关该主题的加州大学伯克利分校的课程材料: http://www-inst.eecs.berkeley.edu/~cs61c/fa15/

In the class I'm taking my teacher is discouraging the students from calling functions recursively. For example, if I want to call the main function in the following code:

if (x > 5) {
    printf("Your number's too high. Enter a number below 5.");
    main();
}

I'm instead encouraged to use:

int x;
while (x > 5) {
    printf("\nYour number's too high. Enter a number below 5.");
    scanf("%d", &x);
}

While I understand that the while function is a simpler way of going about this particular problem, we're being told to avoid recursion in its entirety, especially with main(). However, I thought this was a fairly important concept used in programming. Why should this sort of thing be avoided, especially when calling main()?

解决方案

Great question.

There are types of problems much easier solved with recursion, but in general wherever possible it is usually more efficient to iterate.

The reason for this, in short, is that every time we go into a new function, we have to save the location where we left off along with all the variables that were there, so that when the inner function terminates we can resume in the parent.

Eventually you'll have to remember every parent function's data, which will be a lot, so you'll exhaust your memory. Also the process of saving the data and creating a new context to execute a new function in takes a small amount of time that adds up when you're doing hundreds of thousands of calls.

You can learn more about the sort of cool things that compilers do to make all the things we take for granted (functions, loops) by reading about computer architecture and assembly language.

For example, check out UC Berkeley's class materials on the subject: http://www-inst.eecs.berkeley.edu/~cs61c/fa15/

这篇关于为什么以递归方式调用函数很糟糕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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