Recursion or Iteration?

前端 未结 30 2168
小鲜肉
小鲜肉 2020-11-22 14:44

Is there a performance hit if we use a loop instead of recursion or vice versa in algorithms where both can serve the same purpose? Eg: Check if the given string is a palind

相关标签:
30条回答
  • 2020-11-22 15:27

    Stack overflow will only occur if you're programming in a language that doesn't have in built memory management.... Otherwise, make sure you have something in your function (or a function call, STDLbs, etc). Without recursion it would simply not be possible to have things like... Google or SQL, or any place one must efficiently sort through large data structures (classes) or databases.

    Recursion is the way to go if you want to iterate through files, pretty sure that's how 'find * | ?grep *' works. Kinda dual recursion, especially with the pipe (but don't do a bunch of syscalls like so many like to do if it's anything you're going to put out there for others to use).

    Higher level languages and even clang/cpp may implement it the same in the background.

    0 讨论(0)
  • 2020-11-22 15:28

    There are many cases where it gives a much more elegant solution over the iterative method, the common example being traversal of a binary tree, so it isn't necessarily more difficult to maintain. In general, iterative versions are usually a bit faster (and during optimization may well replace a recursive version), but recursive versions are simpler to comprehend and implement correctly.

    0 讨论(0)
  • 2020-11-22 15:28

    It depends on the language. In Java you should use loops. Functional languages optimize recursion.

    0 讨论(0)
  • 2020-11-22 15:29

    I would think in (non tail) recursion there would be a performance hit for allocating a new stack etc every time the function is called (dependent on language of course).

    0 讨论(0)
  • 2020-11-22 15:30

    Mike is correct. Tail recursion is not optimized out by the Java compiler or the JVM. You will always get a stack overflow with something like this:

    int count(int i) {
      return i >= 100000000 ? i : count(i+1);
    }
    
    0 讨论(0)
  • 2020-11-22 15:30

    Recursion has a disadvantage that the algorithm that you write using recursion has O(n) space complexity. While iterative aproach have a space complexity of O(1).This is the advantange of using iteration over recursion. Then why do we use recursion?

    See below.

    Sometimes it is easier to write an algorithm using recursion while it's slightly tougher to write the same algorithm using iteration.In this case if you opt to follow the iteration approach you would have to handle stack yourself.

    0 讨论(0)
提交回复
热议问题