+ 4

Recursion & Iteration

As far as I have studied every task which can be performed by recursion can also be done by iteration so which one of them is better performance wise? Using what is a good habit?

16th Sep 2017, 9:15 AM
Sahaj Bamba
Sahaj Bamba - avatar
7 Answers
+ 13
Well, It fully depends on what you're trying to do - not all processes will provide an obvious recursive solution. Where they exist, recursive solutions tend to be more elegant, but can potentially be more difficult to understand (most of the times). Recursive functions, mostly, execute more slowly (depending on your environment). As each time a function is called, certain values are placed onto the stack - this not only takes time, but can eat away at your resources if your function calls itself many times. In extreme examples you could run out of stack space. Functions that just iterate make no such demands on stack space, and may be more efficient where memory is limited.
16th Sep 2017, 9:33 AM
Dev
Dev - avatar
+ 1
that means I should always prefer iteration. And is there any particular case anyone know of where iteration doesn't work and recursion does?
16th Sep 2017, 2:24 PM
Sahaj Bamba
Sahaj Bamba - avatar
+ 1
@Prince Do you mean recursion is faster than iteration? I have just done normal programming till now and just came across recursion which I thought works in same way as iteration. I just want you to recommend the performance wise best tool which I should use.
17th Sep 2017, 7:53 PM
Sahaj Bamba
Sahaj Bamba - avatar
0
I like to think of recursion as just another tool. I am aware I can use it, but I will usually just implement an iterative solution if I can think of one.
16th Sep 2017, 2:11 PM
Patrick Fulghum
Patrick Fulghum - avatar
0
someone above said recursion is slow, he/she is totally wrong there is a whole set of programming paradigm which i based on recursiveness if you dare to study algorithm s in future you will come to know how badass recursiveness is also you can't do template meta programming without recursion
17th Sep 2017, 7:06 PM
Prince Gupta
Prince Gupta - avatar
0
other languages naturally lend themselves to recursion I've heard. Iteration gonna be more efficient though.
17th Sep 2017, 11:19 PM
Patrick Fulghum
Patrick Fulghum - avatar