127 Contributors: 10 Thursday, March 2, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial:
Roadmap: roadmap



Note that using recursion can have a severe impact on your code, as each recursive function call will be appended to the stack. If there are too many calls this could lead to a StackOverflowException. Most "natural recursive functions" can be written as a for, while or foreach loop construct, and whilst not looking so posh or clever will be more efficient.

Always think twice and use recursion carefully - know why you use it:

  • recursion should be used when you know the number of recursive calls isn't excessive
    • excessive means, it depends on how much memory is available
  • recursion is used because it is clearer and cleaner code version, it's more readable than an iterative or loop-based function. Often this is the case because it gives cleaner and more compact code (aka less lines of code).
    • but be aware, it can be less efficient! For example in the Fibonacci recursion, to compute the nth number in the sequence, the calculation time will grow exponentially!

If you want more theory, please read:

Related Examples