Using Recursion in C#

前端 未结 10 657
我寻月下人不归
我寻月下人不归 2020-12-14 20:19

Are there any general rules when using recursion on how to avoid stackoverflows?

10条回答
  •  一整个雨季
    2020-12-14 20:49

    Remember, if you have to ask about system limits, then you are probably doing something horribly wrong.

    So, if you think you might get a stack overflow in normal operation then you need to think of a different approach to the problem.

    It's not difficult to convert a recursive function into an iterative one, especially as C# has the Generic::Stack collection. Using the Stack type moves the memory used into the program's heap instead of the stack. This gives you the full address range to store the recursive data. If that isn't enough, it's not too difficult to page the data to disk. But I'd seriously consider other solutions if you get to this stage.

提交回复
热议问题