2

Please help correct my understanding, which is that tail-call optimization works only for recursive calls. What confuses me is that the term is just "tail-call optimization" and not "recursive tail-call optimization".

Or is there some other optimization that happens for tail-calls in general that this term refers to?

1
  • 1
    In theory it could be used for any tail calls. But since the deeper the call chain, the more benefits you reap, it's typically most useful for recursion. Commented Jul 6, 2015 at 9:31

1 Answer 1

4

That's going to be implementation dependent, and compiler dependent - but the fact is, it could be used for any tail call, not only recursive one.

Inlining a method can be easily done for any recursive call, even if it's not the method itself.

A special benefit for it would be for mutual recursive calls:

f(n): //some code g(n) g(n): //some more code f(n-1) 

The question is "what and how to optimize", should we just "cancel" g, and make f recursive?

Fortunately, this problem is relatively simple and is solveable by simple graph algorithms, thanks to the fact that if each method is a node - it has at most one outgoing edge (the single tail call). This means that the graph is actually a series of chains, that form a simple cycle (single cycle in each connected component) at the "worst case", which is easy to handle.

Sign up to request clarification or add additional context in comments.

1 Comment

Your example makes it look like tail-call optimization is the same as inlining, which it isn't. I preferred your answer when it didn't include that misleading example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.