Using Recursion in C#

Ted Smith picture Ted Smith · Mar 4, 2009 · Viewed 23.8k times · Source

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

Answer

Jon Skeet picture Jon Skeet · Mar 4, 2009

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.