Recursive vs Iterative Functions

Iteration vs Recursion

The concepts can sometimes be used interchangeably and they are very similar.

The concept of Recursion and Iteration is to execute a set of instructions repeatedly. The difference between them is that recursion is simply a method call in which the method being called is the same as the one making the call while iteration is when a loop is repeatedly executed until a certain condition is met. Under the hood, both recursion and iteration depends on a condition so as to know when to stop but recursion is simply a process, always applied to a function.

An example of recursion is shown below:

function factorial(number) { 
    if (number === 1) { 
        return 1; 
    return number * factorial(number - 1);
view rawrecursion.js hosted with ❤ by GitHub

and here’s an example of iteration:

var step;
for (step = 0; step < 5; step++) { 
// Runs 5 times, with values of step 0 through 4. 
console.log('Walking east one step');
view rawiteration.js hosted with ❤ by GitHub

Key Differences between Recursion and Iteration

  • A conditional statement decides the termination of recursion while a control variable’s value decide the termination of the iteration statement (except in the case of a while loop).

  • Infinite recursion can lead to system crash whereas, infinite iteration consumes CPU cycles.

  • Recursion repeatedly invokes the mechanism, and consequently the overhead, of method calls. This can be expensive in both processor time and memory space while iteration doesn’t.

  • Recursion makes code smaller while iteration makes it longer.

Memoization makes recursion palatable, but it seems iteration is always faster. Although recursive methods run slower, they sometimes use less lines of code than iteration and for many are easier to understand. Recursive methods are useful for certain specific tasks, as well, such as traversing tree structures.

Recent Posts

See All

Socket Programming in Python

Sockets and the socket API are used to send messages across a network. The network can be a logical, local network to the computer, or one that’s physically connected to an external network like the i

Financial Machine Learning

"The essential tool of econometrics is multivariate linear regression, an 18th century technology that was already mastered by Gauss before 1794...It is hard to believe that something as complex as 21

©2020 by Arturo Devesa.