DEV Community

Discussion on: From recursion to iteration

Collapse
 
itr13 profile image
Mikael Klages

Since your last paragraph can be a little confusing, for anyone that's wondering:
Tail Call Optimization optimizes the iterative function explained in this article, while it's unable to optimize the function in the first example.

Each time a function is called, the program has to allocate memory for all of the parameters used in the functions. These cannot be unallocated until the compiler/interpreter is certain they won't ever be used again.

Normally this means whenever the function is exited, which in the first example first happens after adding "+1" to the return value of the called function.

In the iterative function the returned value won't be modified, so it can deallocate the original function immediately, and only concentrate on the new function call. (I'm paraphrasing a little, optimization might not work exactly like this, and it might do additional optimization, but this is the general gist of the idea behind it)