What is a practical difference between a loop and recursion

前端 未结 9 2683
无人共我
无人共我 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:50

    Loops and recursions are in many ways equivalent. There are no programs the need one or the other, in principle you can always translate from loops to recursion or vice versa.

    Recursions is more powerful in the sense that to translating recursion to a loop might need a stack that you have to manipulate yourself. (Try traversing a binary tree using a loop and you will feel the pain.)

    On the other hand, many languages (and implementations), e.g., Java, don't implement tail recursion properly. Tail recursion is when the last thing you do in a function is to call yourself (like in your example). This kind of recursion does not have to consume any stack, but in many languages they do, which means you can't always use recursion.

提交回复
热议问题