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 Software Developer at Shuttlerock where I write mostly Ruby and Typescript. I also dabble in any language that takes my fancy.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store