What is a practical difference between a loop and recursion

前端 未结 9 2709
无人共我
无人共我 2021-02-19 22:42

I am currently working in PHP, so this example will be in PHP, but the question applies to multiple languages.

I am working on this project with a fiend of mine, and as

9条回答
  •  一个人的身影
    2021-02-19 22:55

    Well, I don't know about PHP but most languages generate a function call (at the machine level) for every recursion. So they have the potential to use a lot of stack space, unless the compiler produces tail-call optimizations (if your code allows it). Loops are more 'efficient' in that sense because they don't grow the stack. Recursion has the advantage of being able to express some tasks more naturally though.

    In this specific case, from a conceptual (rather than implementative) point of view, the two solutions are totally equivalent.

提交回复
热议问题