Are recursive implementations slower than non-recursive implementations?

Renan Schmitt
Java Performance
Published in
4 min readMay 23, 2024

--

In this article, let’s explore the performance of some well-known algorithms that can be implemented using recursive and non-recursive methods.

Factorial

The Factorial algorithm is well-known and is probably the first one every developer has implemented. Here are two implementations of it:

// Recursive Version
private long factorial(long value) {
return value <= 1
? 1
: value * factorial(value - 1);
}

// Non-recursive Version
private long factorial() {
var result = 1L;

for (int i = 2; i < number; i++) {
result = result * i;
}

return result;
}

Here is the comparison of the execution of both versions with numbers up to 500:

We can easily see that the performance of the non-recursive algorithm is better when the input number gets higher. Up to 100, the performance of both algorithms is very similar. Below are the performance results when executing with numbers up to 100k:

Now the performance of the recursive version is three times worse, and one of the main reasons is memory allocation.

--

--

Renan Schmitt
Java Performance

20+ years as a Dev & Architect, mastering Java & ABAP. Passionate about clean code, system architecture, and delivering impactful training.