During my (short) times as a developer, I've come across a few situations where recursive method writing was in order. However, when I look back on a recent conversation I had about recursion, I started wondering why I would ever want to write something recursive. Because it's "clean" code' Because it's cool to say: "hayooo! I wrote something recursive!"? Who knows? One constant factor that is always certain, is that you want to write methods that execute in the most performant way possible. And that is where recursion just won't cut it'
Keeping the old Fibonacci post of a few weeks back in mind, I started investigating versions. The result is a small app that has two methods, one that calulates the x'th number using loops, and one that does the same using recursion.
The result either way:
Already from the beginning, the time difference in calculation between the two methods is noticable. Quite obvious, actually.
So now it's time to do some deeper investigation. For this case, I used a trial version of dotTrace to view the application. When the monitoring of the non-recursive method was done, the big part of the trace was as follows:
10ms to run the actual calculation of the "Looped" method. Nice! No biggie, all is great. Looks performant. Happy feelings. So what about the recursive method? Two simple lines of code vs a little more work in code? Let's see:
Are you kidding me? No of course not. This is kind of expected too, since you always keep on calling methods? And every method call consumes memory, resources... So yeah, big shocker that recursion is not as performant as iteration.
Is that a bad thing? No! Recursion is a great methodology to see things a little different than we normally do. You'll think of the algorithm more than the implementation itself, which to me is a good thing from time to time.
However, if one intends to use recursion in an intensive, deep-leveled method, I'd say think about writing "uglier" code with iterators. It might not save a lot of dev time, but it will probably save you heaps in processing and execution time.
And at the end of the day, execution time is what it's all about, right?
Currently rated 4.5 by 2 people
- Currently 4.5/5 Stars.
- 1
- 2
- 3
- 4
- 5