Alex Rivera | Logout

Recursion or iteration?

Asked 2009-01-26T00:07:55.347
30

I love recursion. I think it simplifies things a lot. Another may disagree; I think it also makes the code a lot easier to read. However, I've noticed that recursion is not used as much in languages such C# as they are in LISP (which by the way is my favorite language because of the recursion).

Does anybody know if there is any good reasons not use recursion in the languages such as C#? Is it more expensive than iteration?

Edit
Report

2 Answers

8

There are many pros and cons to using recursion. Definitely the code simplicity is the biggest one which also lends itself to better code maintainability and less bugs.

The biggest danger to recursion are edge cases were the algorithm spins out of control to break the function stack limit. Some languages, Progress's ABL language for one, has a parameter for the highest level of nested calls allowed. These are usually low and adding recursion to the mix could make an application break that limit.

In short, recursion should always be implemented with tight termination cases otherwise it can be very difficult to debug (because of unpredictability) and can cause serious issues in production code.

For the concerns with memory and speed, unless this is a method itself is short (time wise) being called many times it really doesn't matter what the performance is.

Example: If you use recursion to scan all the files and folders of a hard drive the performance impact that the recursion does is minuscule to the time it takes to hit the hard drive and grab the file system information. In this case recursion is probably preferred over iterative processing.

Another example: If you scan the nodes of a tree structure, an iterative process maybe more beneficial because we are not involving the function stack as much which means we are hitting less memory and probably letting the hardware use more caching. See Robert Gould's response for more details.

answered 2009-01-26T06:26:15.800
6

If an algorithm can be expressed most naturally in a recursive form, and if the stack depth is small (in the log(N) range, i.e. typically <20), then by any means use recursion. (Any performance gain due to iteration will be a small constant factor).

If there is any danger that the stack grows large, and if your language/compiler/runtime system doesn't guarantee the tail call optimization, you should avoid recursive algorithms.

answered 2009-01-26T14:19:24.567

Your Answer