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
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:
Reading and writing .zip files
Recursion in plain English
This modified text is an extract of the original Stack Overflow Documentation created by following contributors
and released under CC BY-SA 3.0