Why should recursion be preferred over iteration?

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

提交回复
热议问题