Are there situations when recursion is necessary, or even strongly preferable to a while loop in javascript or C# (doesn't matter which, usage seems to be the same).
There is a factorial example on MSDN (I removed the irrelevant stuff):
function factorial(num)
{
var tmp = num;
while (num-- > 2) {
tmp *= num;
}
return tmp;
}
vs
function factorial(num)
{
return (num * factorial(num - 1));
}
In short, is there any situation where the second example is preferrable to the first performance wise. Can it EVER accomplish something that the first example can't? If so, what?
Also, recursive algorithms (or implementations) are not inherently slower than iterative ones. In fact, every recursive algorithm can be implemented by an equivalent iterative implementation at the cost of having to keep track some intermediate/temporary values yourself, where the recursive version automatically keeps track of those in the function call stack. - Is recursive code slower than non-recursive code
In short, there is a way to write it iteratively in lieu of a recursive method. Then there comes up questions such as overhead such as in java or python versus the shortcuts that exist in C where your overhead recursion ends up being jumps in the methodology.
In Javascript, recursion is not tail-ended prior to ES2015, so recursion becomes extremely cost-deficient in the long run. Taken from Performance: recursion vs. iteration in Javascript, however after this, Javascript DOES have TER/TCO, so it becomes less costly to invest in recursion. In my opinion, it is a tossup of personal preference between the two in JS. If you can make the recursive functionality and appearance of the code clean and quick, it will perform roughly on par with the iterative version which can become quite heinous to follow and even debug.
In C#, recursion can often be slower than an iterative solution at the cost of readability. However, it again comes down to personal preference. With C# creating overhead and a new stack frame on each "loop/step", it typically is not as performant. In other languages, recursion is as powerful as an iterative solution.
For many languages this is not the case, and recursion is equally or more performant than an iterative version
See: Recursion preferred? for some additional Q/A on why it is preferred in some languages which are not Java, C#, overhead deficient languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With