Algorithms With JavaScript: Recursion vs. Iteration

in #javascript4 years ago

I think one of the most important reasons why we build software is because it can do boring, iterative tasks for us without complaining that they’re too much work and work that’s boring. At least, that’s true if we build our programs right.

There are two ways to repeat the same operation over and over again: iteration and recursion.

Iteration

JavaScript provides a lot of methods for iterations. There are for, while, do while, for in, and for of. Also, there are higher-level loops, like map or forEach. By the way, methods like find, includes, and sort in fact also loop, so use them wisely.

For our example, we’ll be working with for loop. Let’s build our iteration function:

It’s a very simple function that accepts two arguments. The first is number, which we add to the result. The second argument represents how many iterations we will do.

Recursion

JavaScript recursion means that a function calls itself until some condition is met. Let’s build a function with recursion:

As in the first part, the function accepts the same two arguments. Then we check if argument b is equal to 1. If yes, the function returns the first argument. If no, we return the function itself with updated arguments.

Both functions work perfectly fine. Let’s take a look at performance.

Compare Iteration and Recursion Performance

To check how much time it takes to execute functions, we will use the console.time method.
I will start with 200 operations and then grow this number exponentially.

200-operation case:

200 operations: 400 Iteration #1: 1.224ms 400 Recursion #1: 0.258ms

It looks like recursion is much faster than iteration for 200.

2,000 operations:

4000 Iteration #1: 1.501ms 4000 Recursion #1: 1.226ms

Recursion is still faster than iteration, but not by very much, as in the first case.

2000 operations: 40000 Iteration #1: 5.738ms

Recursion:

“Maximum call stack size exceeded.” Wow, what just happened?

We have an error in the recursion case because it adds every function call to the call stack. Every browser has limits on the call stack size. For example, the FireFox maximum call stack is 350,801 and Chrome is 25,237.
But iteration keeps working as much as you humanly can imagine. I added 2 billion operations to test iteration ability. It took some time, but iteration deals with it without complaining:

2000000000 operations: 4000000000 Iteration #1: 8109.370ms

Conclusion

It looks like recursion is less expensive compared to iteration. But we should be careful and not give recursion more than it could handle.

You can play with it in repl.

Always happy for your feedback. Thanks for reading!