What is the difference between iteration and recursion?

后端 未结 8 799
太阳男子
太阳男子 2021-01-30 11:52

What is the difference between iteration and recursion and why/when is one better:

while (true) {
    // Iterating
}

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-30 12:18

    The main difference between recursion and iteration is memory usage.

    For every recursive call needs space on the stack frame resulting in memory overhead.

    Let me give you an example. Imagine in one case you forgot to write the base case for your recursive function resulting in endless recursive calls and in other case you wrote an infinite loop.

    Since every recursive function assigns new memory space, in first case your code will give a stack overflow exception but in second case it will keep running forever.

    So it better to make your iterative code more understandable than using Recursion.

提交回复
热议问题