+ 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?
6 ответов
+ 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.
+ 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?
+ 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.
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.
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
0
other languages naturally lend themselves to recursion I've heard. Iteration gonna be more efficient though.