为什么递归优于迭代? [英] Why should recursion be preferred over iteration?

查看:15
本文介绍了为什么递归优于迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

迭代比递归更高效,对吧?那么为什么有些人认为递归比迭代更好(用他们的话来说更优雅)?我真的不明白为什么像 Haskell 这样的语言不允许迭代并鼓励递归?鼓励性能不佳的东西不是很荒谬(当更多性能选项(即递归可用)时也是如此)?请对此有所了解.谢谢.

Iteration is more performant than recursion, right? Then why do some people opine that recursion is better (more elegant, in their words) than iteration? I really don't see why some languages like Haskell do not allow iteration and encourage recursion? Isn't that absurd to encourage something that has bad performance (and that too when more performant option i.e. recursion is available) ? Please shed some light on this. Thanks.

推荐答案

迭代比递归,对吧?

Iteration is more performant than recursion, right?

不一定.这个概念来自许多类似 C 的语言,在这些语言中调用函数(无论是否递归)都会产生很大的开销,并且会为每次调用创建一个新的堆栈帧.

Not necessarily. This conception comes from many C-like languages, where calling a function, recursive or not, had a large overhead and created a new stackframe for every call.

对于许多语言,情况并非如此,递归与迭代版本的性能相同或更高.如今,甚至一些 C 编译器将一些递归构造重写为迭代版本,或者将堆栈帧重用于尾递归调用.

For many languages this is not the case, and recursion is equally or more performant than an iterative version. These days, even some C compilers rewrite some recursive constructs to an iterative version, or reuse the stack frame for a tail recursive call.

这篇关于为什么递归优于迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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