While writing code and algorithms you should consider tail call optimization (TCO).

What is tail call optimization?

The tail call optimization is the fact of optimizing the recursive functions in order to avoid building up a tall call stack. You should as well know that some programming languages are doing tail call optimizations.

For example, Python and Java decided to don’t use TCO. While JavaScript allows to use TCO since ES2015-ES6.

Even if you know that your favorite language support natively TCO or not, I would definitely recommend you to assume that your compiler/interpreter will not do the work for you.

How to do a tail call optimization?

There are two famous methods to do a tail call optimization and avoid tall call stacks.

1. Going bottom-up

As you know recursions are building up the call stack so if we avoid such recursions in our algorithms it will will allow us to save on the memory usage. This strategy is called the bottom-up (we start from the beginning, while a recursive algorithm starts from the end after building a stack and works backwards.)

Let’s take an example with the following code (top-down — recursive code):

function product1ToN(n) {
  return (n > 1) ? (n * product1ToN(n-1)) : 1;
}

As you can see this code has a problem: it builds up a call stack of size O(n), which makes our total memory cost O(n). This code makes us vulnerable to a stack overflow error, where the call stack gets too big and runs out of space.

In order to optimize our example we need to go bottom-down and remove the recursion:

function product1ToN(n) {
  let result = 1;
  for (let num = 1; num <= n; num++) {
    result *= num;
  }
  return result;
}

This time we are not stacking up our calls in the call stack, and we do use a O(1) space complexity(with a O(n) time complexity).

#memoization #programming #algorithms #optimization #optimize

Optimize Your Algorithms Tail Call Optimization
1.65 GEEK