Why should recursion be preferred over iteration?

前端 未结 18 1150
既然无缘
既然无缘 2020-11-29 18:50

Iteration is more performant than recursion, right? Then why do some people opine that recursion is better (more elegant, in their words) than iteration? I really don\'t see

相关标签:
18条回答
  • 2020-11-29 19:24

    Iteration is just a special form of recursion.

    0 讨论(0)
  • 2020-11-29 19:29

    As a low level ITERATION deals with the CX registry to count loops, and of course data registries. RECURSION not only deals with that it also adds references to the stack pointer to keep references of the previous calls and then how to go back.-

    My University teacher told me that whatever you do with recursion can be done with Iterations and viceversa, however sometimes is simpler to do it by recursion than Iteration (more elegant) but at a performance level is better to use Iterations.-

    0 讨论(0)
  • 2020-11-29 19:31

    I would compare recursion with an explosive: you can reach big result in no time. But if you use it without cautions the result could be disastrous.

    I was impressed very much by proving of complexity for the recursion that calculates Fibonacci numbers here. Recursion in that case has complexity O((3/2)^n) while iteration just O(n). Calculation of n=46 with recursion written on c# takes half minute! Wow...

    IMHO recursion should be used only if nature of entities suited for recursion well (trees, syntax parsing, ...) and never because of aesthetic. Performance and resources consumption of any "divine" recursive code need to be scrutinized.

    0 讨论(0)
  • 2020-11-29 19:37

    Iteration is more performant than recursion, right?

    Not necessarily. This conception comes from many C-like languages, where calling a function, recursive or not, had a large overhead and created a new stackframe for every call.

    For many languages this is not the case, and recursion is equally or more performant than an iterative version. These days, even some C compilers rewrite some recursive constructs to an iterative version, or reuse the stack frame for a tail recursive call.

    0 讨论(0)
  • 2020-11-29 19:37

    Haskell do not allow iteration because iteration involves mutable state (the index).

    0 讨论(0)
  • 2020-11-29 19:38

    I think it would help to get some understanding of what performance is really about. This link shows how a perfectly reasonably-coded app actually has a lot of room for optimization - namely a factor of 43! None of this had anything to do with iteration vs. recursion.

    When an app has been tuned that far, it gets to the point where the cycles saved by iteration as against recursion might actually make a difference.

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