+ 2
Fibonacci (both loop and recursion). And in Netbeans, it showed that recursion is 14s later than loop. Should we avoid recursion
4 Réponses
+ 4
its true that recursion is more resource intensive than using a basic for loop. you probably want to avoid recursion unless its a question in an interview, then you should at least know how it works
+ 4
In some cases recursion is very inefficient, because you calculate certain values more than once. Imagine you want to compute the seventh Fibonacci number f(7). By definition this is f(5)+f(6). Now f(6) is f(5)+f(4) and we already see, that we have to do the computation for f(5) twice. f(4) will be computed four times and so on.
That will not always be an issue. If you compute the factorial recursively, for example. You could also mitigate these types of problems by saving values and looking them up, rather than recomputing them.
+ 1
It depends. In languages that heavily rely on recursion, i.e. functional ones, the compiler will often optimize for it.
0
nice answer @Tobi. now i know why recursion is so inefficient in solving Fibonacci case.