Iteration vs Recursion, lets Benchmark it!
One of my favorite challenges from Week 1 at DBC was looking at pros and cons of writing a method iteratively vs recursively. So naturally I had to blog about it.
Lets use the classic - calculate the nth number of the Fibonacci sequence as an example:
Fibonacci - iterative
Fibonacci - recursive
We can measure a program’s runtime by using Ruby’s handy Benchmark module.
As you can see, my recursive solution performs far worse in terms of runtime than it’s iterative counterpart. This is because our method re-calculates all of the preceeding numbers every time it is run.
What if instead we tell our method to remember the results of our earlier calculations? That’s the concept behind Memoization. We can create an empty hash to store temporary results and have our program check if that calculation has been done already. If it has, we can just pull the stored result.
Refactoring our recursive solution:
Fibonacci recursive - refactored
As you can see, our runtimes are now much more comparable!
References: