Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion or iteration?

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?

like image 447
Tom Avatar asked Jan 26 '09 00:01

Tom


People also ask

What is difference between recursion and loop?

The difference between recursion and loop is that recursion is a mechanism to call a function within the same function while loop is a control structure that allows executing a set of instructions again and again until the given condition is true.

Why iteration is faster than recursion?

In a Von Neumann Architecture, clearly "Iteration" is a simpler/basic concept than “Recursion". We have a form of "Iteration" at level 7, while "Recursion" is at level 14 of the concepts hierarchy. Iteration will always be faster in machine code because it implies less instructions therefore less CPU cycles.


1 Answers

Are they more expensive than iterations?

Yes they are. Many Lisp variants support the idea of a "tail-call optimisation" which allows many uses of a recursive function call to be converted into an iterative one (this is simplifying a bit). If tail-call is not supported, then a recursive function call will use progressively more memory on the stack.

like image 179
1800 INFORMATION Avatar answered Sep 22 '22 22:09

1800 INFORMATION