| Author |
inefficient
|
sameera liyanage
Ranch Hand
Joined: Nov 25, 2008
Posts: 643
|
|
|
is it better use loop than recursive method calling
|
 |
Sagar Rohankar
Ranch Hand
Joined: Feb 19, 2008
Posts: 2896
|
|
Its depends upon the scenario, the requirements, and your expertise,
Here are some points
Recursion is, many time, easy to read and understand than loops, loop may some times gets messy with logic of multiple return statement.Recursion increased the work for JVM, by maintaining the stacks for each function call, exit point etc, where as loop can be straight forward, not much overload to JVM
Finally I suggest if there are some less iterations to be done , then use Recursion, but if iterations are increased it may gets results in to StackOverflowException (very rare), In such case loops are friendly..
Still the answer is, depends upon your need
You can Google for this question use loop than recursive method , anytime
|
[LEARNING bLOG] | [Freelance Web Designer] | [and "Rohan" is part of my surname]
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
If you can use a loop you should use a loop, because of the stack overhead. In a loop, all local variables will be reused instead of having separate variables per method invocation. Sometimes it makes sense to use a recursive call though, especially when using tree-type structures (like a file system), or if an algorithm is clearly designed to be called recursively (e.g. the most basic version of Fibonacci: f(n) = f(n - 1) + f(n - 2)).
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Sagar Rohankar
Ranch Hand
Joined: Feb 19, 2008
Posts: 2896
|
|
Rob Prime wrote: Sometimes it makes sense to use a recursive call though, especially when using tree-type structures (like a file system),
Yes, You can see many tree algorithms are explained by using recursion, like DFS, Finding Height, etc
|
 |
 |
|
|
subject: inefficient
|
|
|