What is a tail call
When the last step in a function is to call another function
To optimize the
- The tail call is different from other calls because of its particular call location. As we know, function calls form a “call record” in memory, also known as a “call frame”, which holds information such as the location of the call and internal variables. If function B is called from inside function A, then A call record of B is formed above the call record of A. When B finishes running and returns the result to A, B’s call record disappears. If C is also called from inside function B, there is a stack of C calls, and so on. All the records of the calls form a “call stack”.
- The last call is the last operation of the function, so there is no need to keep the call record of the outer function, because the call location, internal variables and other information will not be used, as long as the call record of the inner function is directly replaced by the call record of the outer function.
function f() { let m = 1; let n = 2; return g(m + n); } f(); Function f() {return g(3); } f(); // same as g(3);Copy the code
- In the above code, if g is not a tail call, f needs to store the values of the internal variables M and n, the location of g’s call, and so on. However, since function f ends after g is called, it is completely possible to delete the call record of f() and keep only the call record of g(3) when executing the last step
- This is known as “Tail Call optimization,” where only calls to the inner functions are kept. If all functions are tail calls, then it is perfectly possible to record only one call per execution, which would save a lot of memory. This is what tail-call optimization is all about.
Tail recursion
- The function calls itself, called recursion. If the tail calls itself, it is called tail recursion. – Recursion is very memory intensive, because you need to keep hundreds or thousands of call records at the same time, which is prone to “stack overflow” errors. For tail recursion, however, there is only one call record, so the “stack overflow” error never occurs.
- Tail-recursion implementations often require rewriting the recursive function to ensure that the last step calls only itself. The way to do this is to rewrite all the internal variables used as arguments to the function