• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

inefficient

 
sam liya
Ranch Hand
Posts: 1240
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is it better use loop than recursive method calling
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
     
    Rob Spoor
    Sheriff
    Pie
    Posts: 20512
    54
    Chrome Eclipse IDE Java Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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)).
     
    Sagar Rohankar
    Ranch Hand
    Posts: 2907
    1
    Java Spring Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic