Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion versus manual stacks - Which is preferred in which case?

A recursive program creates a stack internally, and causes the users to write less code.

Are there any cases where recursion is actually preferred over manual stacks for the reason other than mentioned above?

EDIT 1:

In what way is dynamic memory allocation more "expensive" than the allocations on the heap by a recursive program?

like image 388
Aquarius_Girl Avatar asked Feb 02 '12 03:02

Aquarius_Girl


1 Answers

The main reason, which I think you're alluding to when you say "less code", is clarity and simplicity of design. In a language with features like local variables and automatic storage, it is infinitely more natural to use those features than to structure everything into home-rolled stacks. (After all, why use functions at all? Why not write your entire program using if/else and while as your only control structures?)

Another consideration is performance, especially in multithreaded environments. Recursion — depending on the language — is likely to use the stack (note: you say "creates a stack internally", but really, it uses the stack that programs in such languages always have), whereas a manual stack structure would require dynamic memory allocation, which frequently has a noticeable performance penalty — not to mention the added complexity of making sure that you release all that memory when you (say) encounter an exception.

like image 122
ruakh Avatar answered Sep 19 '22 11:09

ruakh