Using Recursion in C#

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

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

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 20:44

    How many times you will be able to recurse will depend on:

    • The stack size (which is usually 1MB IIRC, but the binary can be hand-edited; I wouldn't recommend doing so)
    • How much stack each level of the recursion uses (a method with 10 uncaptured Guid local variables will be take more stack than a method which doesn't have any local variables, for example)
    • The JIT you're using - sometimes the JIT will use tail recursion, other times it won't. The rules are complicated and I can't remember them. (There's a blog post by David Broman back from 2007, and an MSDN page from the same author/date, but they may be out of date by now.)

    How to avoid stack overflows? Don't recurse too far :) If you can't be reasonably sure that your recursion will terminate without going very far (I'd be worried at "more than 10" although that's very safe) then rewrite it to avoid recursion.

提交回复
热议问题