Erlang 中的尾递归与前向递归
在 erlang 中,尾递归比前向递归的性能更好吗?
或者erlang编译器也优化了前向递归?
我的意思是,有什么理由使用尾递归而不是前向递归吗?
在我看来,前向递归看起来更漂亮。
Is tail recursion better than forward recursion for perfomance in erlang?
Or erlang compiler optimizes forward recursion too?
I mean, are there any reasons to use tail recursion instead of forward recursion?
In my opinion, forward recursion looks more pretty.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尾递归和前向递归是完全不同的概念。
请参阅此讨论。
可以编写尾递归的前向递归,从而进行优化。也可以编写一个非尾递归的前向递归:在这种情况下,它将不会被优化,即它将消耗堆栈空间。
Tail recursion and forward recursion are totally different concepts.
See this discussion.
It is possible to write a forward recursion that is tail recursive, and thus optimized. It is also possible to write a forward recursion that is not tail recursive: in this case, it will not be optimized, i.e. it will consume stack space.
尾递归通常更好,因为它使用更少的内存。您只需将需要的内容带入下一次调用,从而最大限度地减少堆栈上的内存利用率。此外,当优化尾递归代码时,不需要的函数返回将被丢弃,这将使其在某些情况下稍微快一些。
例如,如果一个函数的返回值是对另一个函数的调用,则无需将中间函数保留在堆栈上。所以代码从内部函数直接跳回调用者。
在某些情况下,Erlang 编译器将非尾递归优化为尾递归,但不要指望它。尽可能养成编写尾递归函数的好习惯。
Tail recursion is usually better because it uses less memory. You only bring what you need onto the next call, which minimizes memory utilization on the stack. Also, when the tail recursive code is optimized, function returns that are not needed are thrown away which will make it slightly faster in some cases.
For example, if a function's return value is the call to another function, there is no need to keep the intermediary function on the stack. So the code jumps back directly to the caller from the inner function.
Non-tail recursion is optimized to tail recursion in some cases by the Erlang compiler, but don't count on it. Make it a good habit to code tail recursive functions whenever you can.