Recursion is a topic most beginner programmers fear and when you get the hang of it, it works like magic (Congrats! Not a noob anymore). When someone introduces recursion, they say it’s basically a function which calls back itself, and your brain goes like WHAAAAAT??
3. Three magic words: tail call optimization: Some functional languages implement this wizardry. So basically, what happens is, if a function’s return expression is a result of a function call, the stack frame is reused instead of pushing a new stack frame in the call stack. Sadly, only a few imperative languages have this wizardry.
The secret magic of tail call
A lot of programmers avoid using recursion and believe that it is less efficient than it’s iterative counterparts.
- space is carved out on the stack for function arguments and variables.
- arguments are copied into this new space
- control jumps to the function
- function code runs
- function results are copied into the new value
- stack rewounds to its previous position
- control jumps back to the caller