Why should recursion be preferred over iteration?

前端 未结 18 1213
既然无缘
既然无缘 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:48

    Iteration is more performant than recursion, right?

    Yes.

    However, when you have a problem which maps perfectly to a Recursive Data Structure, the better solution is always recursive.

    If you pretend to solve the problem with iterations you'll end up reinventing the stack and creating a messier and ugly code, compared to the elegant recursive version of the code.

    That said, Iteration will always be faster than Recursion. (in a Von Neumann Architecture), so if you use recursion always, even where a loop will suffice, you'll pay a performance penalty.

    Is recursion ever faster than looping?

提交回复
热议问题