+ 2

Fibonacci (both loop and recursion). And in Netbeans, it showed that recursion is 14s later than loop. Should we avoid recursion

https://code.sololearn.com/ccSl3tYECX9C/?ref=app

19th Apr 2017, 3:07 AM
Thang Nguyen
Thang Nguyen - avatar
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
19th Apr 2017, 4:20 AM
Edward
+ 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.
19th Apr 2017, 8:07 AM
Tob
Tob - avatar
+ 1
It depends. In languages that heavily rely on recursion, i.e. functional ones, the compiler will often optimize for it.
19th Apr 2017, 5:01 AM
1of3
1of3 - avatar
0
nice answer @Tobi. now i know why recursion is so inefficient in solving Fibonacci case.
19th Apr 2017, 8:13 AM
Thang Nguyen
Thang Nguyen - avatar