Lecture 10

Recursion vs Iteration

MCS 275 Spring 2023
Emily Dumas

Lecture 10: Recursion vs Iteration

Reminders and announcements:

  • Homework 4 due Tuesday at Noon
  • Project 1 autograder open! 🥳
  • Project 1 due Friday at 6pm
  • Project 2 will be posted next Monday, due Feb 28

Iterative solutions

Let's write iterative versions of factorial, Fibonacci, and paper folding. (Or as many as time allows.)

Timing comparison

Let's compare the running time of the iterative and recursive solutions.

Question

Why is recursive fact() somewhat competitive, but fib() is dreadfully slow?

Let's track the number of function calls.

fact call graph

fib call graph

fib call graph

Memoization

fib computes the same terms over and over again.

Instead, let's store all previously computed results, and use the stored ones whenever possible.

This is called memoization. It only works for pure functions, i.e. those which always produce the same return value for any given argument values.

math.sin(...) is pure; random.random() is not.

memoized fib call graph

memoized fib call graph

Fibonacci timing summary

n=35 n=450
recursive 1.9s > age of universe
memoized recursive <0.001s 0.003s
iterative <0.001s 0.001s

Measured on my old office PC (2015, Intel i7-6700K) with Python 3.8.5

Memoization summary

Recursive pure functions with multiple self-calls often benefit from memoization.

Memoization does not alleviate recursion depth limits.

Memoization trades running time for memory consumption.

References

Revision history

  • 2022-02-09 Last year's lecture on this topic finalized
  • 2023-02-06 Updated version for spring 2023