1 min readMay 21, 2020

Comparing the two Factorial algorithms with bigger numbers highlights the cost of the naive recursive approach:

When comparing the Fibonacci algorithms, even smaller inputs are needed to expose the cost of the recursive approach (i.e. 10):

If you fancy trying even larger numbers, you’ll quickly see even worse performance from the recursive Fibonacci algorithm you’ve used. This is because there’s no tail recursion optimisation done by (most) javascript (implementations). Therefore, you end up repeating a lot of work and, before long, overflowing the stack.

You can re-write the recursive solution such that it doesn’t do that like so:

Indeed, it can even handle much, much larger inputs:

It still under-performs against the iterative solution when the inputs get larger, but it doesn’t overflow the stack.


I’m a Lead Developer and write mostly Ruby on Rails. I also dabble in any language that takes my fancy.