11.5 Recursion vs. Iteration

We’ve studied functions factorial and fibonacci, which can be implemented either recursively or iteratively. In this section, we compare the two approaches and discuss why you might choose one approach over the other in a particular situation.

Both iteration and recursion are based on a control statement: Iteration uses an iteration statement (e.g., for or while), whereas recursion uses a selection statement (e.g., if or ifelse or ifelifelse):

Negatives of Recursion

Recursion has many negatives. It repeatedly invokes the mechanism, and consequently the overhead, of function calls. This overhead can be expensive in terms of both processor time and memory space. Each recursive call causes another copy of the function (actually, only the function’s variables, stored in the stack frame) to be created—this set of copies can consume considerable memory space. Iteration avoids these repeated function calls and extra memory assignments. However, for some algorithms that are easily expressed and understood with recursion, iterative solutions are not readily apparent.