开发者

Tail Recursion vs Forward recursion in Erlang

Is tail recursion better than forward recursion for perfomance in erlang?

Or er开发者_C百科lang 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜