Recursion
suggest changeRemarks
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:
- https://www.cs.umd.edu/class/fall2002/cmsc214/Tutorial/recursion2.html
- https://en.wikipedia.org/wiki/Recursion#In_computer_science
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents