为什么递归比迭代更受欢迎?

问题描述:

迭代比递归更高效,对吧?那么为什么有些人认为递归比迭代更好(用他们的话来说更优雅)?我真的不明白为什么像 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.