Recursion vs Iteration — Are you writing efficient code?

Nandish swarup
2 min readMar 13, 2021

Photo by Ketut Subiyanto from Pexels

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

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Nandish swarup
Nandish swarup

Written by Nandish swarup

Android | Kotlin | Full stack developer | Blogger

No responses yet

Write a response