From a theoretical point of view, solving problems using loops is faster than a recursive way.
However, I checked this statement on the .NET platform and found that there are practically no differences. Probably, .NET developers have recently done a good job of optimization. (At least in shallow depths of recursion).
However, there are tasks that can only be solved recursively (try solving the problem of towers of Hanoi with loops).
I use the following rule:
if the problem-solving algorithm can be visualized, but it is difficult to translate it directly into code expressions, then recursion will help.
1. Which one is better?
-> For programs which are small and aren't compute intensive use the one you prefer.
When speed & memory becomes an issue consider looping.
2. Are loops faster than recursion?
-> Loops are generally faster than recursion(excluding when compilers can optimize into a loop) in most languages.
3. Is recursion bad?
-> Recursion is not necessarily bad; It's the performance(too long to compute) and memory usage which is.
1. While compilers (interpreters don't do this) can eliminate the stack frames. You can't get a stack trace -- debug without stackframes.
2. If the compiler doesn't automatically do tail-call-elimination. You need to manually do it by adding an accumulator, decreasing the count. Which makes it a little complicated and harder to grasp compared to regular recursion.
Hey Basil, Iterative version of "Tower of Hanoi" ;) https://www.geeksforgeeks.org/iterative-tower-of-hanoi/
I think as more complex is the stop condition, more recommended will be the use of recursion. For simple conditions, i believe there is no need to use recursion, unless you reduce the Code.
A good exemple of the use of recursion, in my view, is in therms that involve "Fork and Join" to optimize tasks by taking advantage of multiprocessing.
If you are more comfortable creating loops or functions you will find most coding easiest in your comfort zone. Recursion uses more stack memory than loops but uses less program memory. Everything in programming is a tradeoff: simplicity, speed, reusability, memory and ease of debugging are just a few things to be considered. Sometimes the simplest solution is also the fastest and most efficient method, while other times the more complex and elegant solutions are faster. Select what's comfortable for you, get it working, then try to improve upon it. Well documented code during testing will also be easier to fix or modify for other purposes later.
I’m not a programmer (‘cause I’m more a system programmer) but, more or less, I’m programming since 40 years and I really used recursion, into a production code, one time only (finding it perfect for that case).