Recursion vs Iteration — Are you writing efficient code?

The basic concept of iteration and recursion are the same i.e execution of the same set of instructions again and again. Let’s have a look at both of them using a simple example to find the factorial of a number
Iteration:
In iteration loop repeatedly executes until the controlling condition becomes false
private static int factorialIterative(int number) {
int ans = 1;
for (int i = 2; i <= number; i++) {
ans *= i;
}
return ans;
}
Recursion:
In recursion, the method calls itself repeatedly until a condition is met.
private static int factorialRecursion(int number) {
if (number == 0)
return 1;
else
return number * factorialRecursion(number - 1);
}
Recursion vs Iteration
Time Complexity:
Recursion: Time complexity of recursion can get exponential when there are more recursive calls.
Iteration: Time complexity is usually lesser than recursion.
Code Size:
Recursion: Recursion decreases the size of the code.
Iteration: Iterative code tends to be bigger in size.
OverHead:
Recursion: Since recursion involves calling the same function again and again it requires a stack to maintain state of all functions calls
Iteration: This does not involve any such overhead.
Infinite Repetition:
Recursion: If there is some mistake in defining base condition which is responsible for ending the recursion then it will never stop executing and will result in CPU crash
Iteration: It can occur because of some error in iterator assignment or in the terminating condition which may lead to infinite loops resulting in a system error. It will stop executing as long as memory is exhausted but will never cause CPU crash.
Since iteration does not involve overhead to maintain stacks making it faster to execute. It is also safer than recursion in case of an infinite loop. Hence we can state that iterative methods are better than recursive in most cases
That's it for now!!
Thanks for reading and don’t forget to share with your fellow developers :)
This post was originally posted on CodeTheraphy.com.
For more articles follow me on Medium and CodeTheraphy.com you can also connect me on LinkedIn