3 ms·
It's probably a good best practice to avoid recursion when possible. In practice it often makes your code harder to reason about and/or slower to run. Most com
by marginalia_nu 4y ago
It's probably a good best practice to avoid recursion when possible. In practice it often makes your code harder to reason about and/or slower to run.
Most commonly used programming languages will be slower to recurse than to loop using "for" or "while". Not all languages have tail call optimization and it can be difficult to reason about when tail call optimization is applicable.
That said, there are programming languages where recursion is literally how you loop, so it's not that it's bad so much as that these languages are in the minority.
- warrenm 4y agoI find recursive code far easier to read (>90% of the time) ... but it's often not the most optimal solution The classic, literally "textbook", example is solving the Fibonacci sequence Where F(N) = F(N-1) + F(N-2) AND F(0) = 1 AND F(1) = 1 You have a pair of base cases / definitions But then the rest of the solution is trivial to implement (even most-obviously, to some people) implemented in its recursive form :)
- marginalia_nu 4y agoFibonacci is pretty much cherry picked to make recursive definitions look good. It's not that far from a function like the Collatz sequence, which will may just earn you a Fields medal if you're able to say for certain what it will return for all given inputs.