Tail call optimization

Also known as: tail call elimination

On this page 7

Tail call optimization (TCO), also called tail call elimination, is a compiler or runtime technique that executes a function call in tail position by reusing the caller’s stack frame instead of pushing a new one. Because the caller has no remaining work after such a call, its frame is no longer needed, and the call can be compiled as a jump rather than a call. The result is that properly written recursive functions run in constant stack space.

In functional programming, where loops are usually expressed as recursion, this guarantee is essential. Languages such as Scheme require it by specification, while others offer it only partially or not at all, which directly affects how programmers write iterative algorithms.

How tail call optimization works

A call is in tail position when its result is returned directly by the enclosing function, with no further computation, conversion or cleanup afterward. In return f(x), the call to f is a tail call; in return 1 + f(x), it is not, because the addition still has to run after f returns.

A normal call pushes a return address and a new stack frame, holding arguments and local variables. With tail call optimization, the compiler instead overwrites the current frame with the new arguments and jumps to the callee, which later returns straight to the original caller. Stack depth therefore stays the same no matter how many tail calls happen in sequence.

The following table contrasts what happens at the machine level in each case.

AspectOrdinary callOptimized tail call
Stack frameNew frame pushedCurrent frame reused
Control transferCall instructionJump instruction
Return pathBack through every callerDirectly to the original caller
Stack growth for n callsProportional to nConstant
Stack traceShows every callerIntermediate callers disappear
Ordinary call compared with an optimized tail call

Tail recursion and the accumulator pattern

The most common application is tail recursion, where a function calls itself in tail position. A naive factorial multiplies after the recursive call returns, so each level keeps a pending operation on the stack. Rewriting it with an accumulator parameter moves the multiplication before the call, turning the recursion into a loop in disguise.

For example, fact(n, acc) returns acc when n is zero and otherwise returns fact(n - 1, n * acc). Every recursive call is now a tail call, so an optimizing compiler generates code equivalent to a while loop with two variables. This transformation is one of the first techniques taught in functional programming courses because it converts linear stack usage into constant stack usage.

Not every recursive function can be rewritten this easily. Tree traversals and other algorithms with multiple recursive calls usually keep at least one non-tail call. They can still avoid deep stacks through continuation-passing style, where pending work is packaged into a closure and passed forward, at the cost of allocating those closures on the heap.

General tail calls and mutual recursion

Full tail call optimization covers any call in tail position, not only self-recursion. This matters for mutually recursive functions, such as a state machine in which even(n) calls odd(n - 1) and odd calls even. With proper tail calls, such functions can run for millions of steps without growing the stack.

Some compilers implement only self tail call elimination, rewriting a function that calls itself into a loop, but leave calls to other functions untouched. The distinction is significant: interpreters written as a set of mutually calling handlers, and code in continuation-passing style, depend on the general form. The table below shows the levels of support a language can provide.

LevelWhat is optimizedTypical examples
Guaranteed proper tail callsEvery tail call, by specificationScheme, Standard ML implementations
Self recursion onlyDirect calls to the same functionScala with @tailrec, Kotlin tailrec
Best-effort optimizationTail calls when the optimizer decidesC and C++ compilers at higher optimization levels
No eliminationNothing; every call uses a framePython, Java virtual machine bytecode
Levels of tail call support

Language and runtime support

Support for tail call optimization varies widely, and portable code cannot assume it unless the language standard guarantees it. Scheme has required proper tail calls since its early reports, and many ML and Erlang implementations rely on them for server loops. Haskell uses lazy evaluation and a different execution model, so stack behavior depends more on strictness than on tail position.

LanguageTail call behaviorPractical consequence
SchemeRequired by the standardRecursion is the normal loop construct
ErlangGuaranteed for tail callsLong-running process loops are recursive
ScalaSelf recursion with @tailrecCompiler reports an error if the call is not a tail call
JavaScriptSpecified in ES2015, rarely implementedOnly some engines perform it
PythonDeliberately not providedRecursion limit of about 1,000 frames by default
C and C++Optimizer dependentBehavior changes with compiler flags
Tail call behavior in common languages

The Java virtual machine has no native tail call instruction, which is why Scala and Kotlin restrict their guarantee to self recursion that can be compiled into a loop. Python’s designers have rejected the feature partly to keep complete stack traces for debugging.

Benefits, costs and common misconceptions

The main benefit is safety from stack overflow in deep or unbounded recursion, which makes recursion a reliable replacement for loops. A secondary benefit is speed: a jump is cheaper than a full call and return, and reusing the frame improves cache locality. The main cost is lost debugging information, because eliminated frames no longer appear in stack traces.

Several misunderstandings appear repeatedly in practice, and the table below lists the most frequent ones with their corrections.

MisconceptionRealityConsequence
Any final line is a tail callWork after the call disqualifies itStack still grows unexpectedly
All recursion is optimizedMany languages offer no guaranteeStack overflow on large inputs
Exception handlers are harmlessA surrounding try block keeps the frame aliveOptimization silently disabled
Destructors do not matterC++ cleanup after the call blocks eliminationFrame cannot be reused
TCO changes resultsIt changes only resource usageSemantics stay identical
Frequent misconceptions about tail calls

Where the language offers no guarantee, programmers use a trampoline: each step returns a small object describing the next call, and a driver loop invokes it repeatedly. This simulates proper tail calls at the cost of extra allocation per step, and it is common in JavaScript and Python libraries.

Put simply

Every time a program calls a function, it leaves a note saying where to come back. If a function calls itself thousands of times, those notes pile up until memory runs out.

Tail call optimization notices when a function has nothing left to do after its last call. In that case, there is no reason to keep the old note, so the program throws it away and reuses the space. It is like passing a task directly to a colleague and going home, instead of waiting at the desk to forward the answer. The key takeaway is that well-structured recursion can then run as long as needed without exhausting memory.

In practice

A telecommunications team runs a message broker written in Erlang, where each client connection is a lightweight process. Every process runs a loop function that waits for a message, handles it and then calls itself with the updated state as an argument. A single connection may stay open for weeks and process several million messages.

Because Erlang guarantees proper tail calls, that recursive loop occupies the same small stack frame for its whole lifetime, and a node comfortably hosts hundreds of thousands of such processes. During a code review, a developer wrapped the recursive call in a logging statement that ran after the call returned. Memory per process began to grow steadily under load testing, and moving the logging before the call restored constant memory use, a clear demonstration that tail position must be preserved deliberately.