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 Senior Software Developer at Flick Electric where I write mostly Ruby on Rails. I also dabble in any language that takes my fancy.

Love podcasts or audiobooks? Learn on the go with our new app.

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
Adam Henley (He/Him)

Adam Henley (He/Him)

I’m a Senior Software Developer at Flick Electric where I write mostly Ruby on Rails. I also dabble in any language that takes my fancy.

More from Medium

Singularity.Net: Why we need AI on the blockchain.

Why Don’t New Car’s Last “Like They Used To”

Welcome to the Regular Season Finale Week 18 of The OSG Report.