Recursion is normally limited to stack depth. On systems with limited
stack space or where the recursion depth may exceed the stack size,
iteration may work better.
Also, many compilers can optimize loops where has optimizing recursion
is a much more difficult thing. Some optimizers can use iteration
machine language instructions (such as loop) to even further optimize
iteration.
Recursion requires the stacking and unstacking of registers (PC, frame
pointer, parameters, etc.). This will also slow down recursion vs
iteration.
Recursion has its uses but should not be used just to be cute or
clever. The programmer should weigh the benefits of both before deciding.
For example, I wrote a function to display directories and when it
encountered a sub-directory it called itself to display the sub-directory.
On 2/17/2025 11:41 AM, Chuck Guzis via cctalk wrote:
While a hardware stack may be useful, I don't
consider it to be
essential and perhaps counter-productive. (dodging brickbats).
I say that because if a recursive solution to a problem is available on
a stack-oriented architecture, the natural impulse is to program a
recursive solution. Lack of hardware support for recursion might
otherwise push one toward an iterative approach, which in many cases can
perform better.
--Chuck