C# Recursion Depth - How Deep can you go

C#.NetRecursionStack

C# Problem Overview


Is there any control how much you can Recursively call something?

From a basic test program I get a recursion depth of just over 18k

which depends on the stacksize....

is there a way to set up a chunk of memory (perhaps a thread) with a massive stack to increase recursion depth?

C# Solutions


Solution 1 - C#

I've increased the stack size during some documents recognition. It was really needed.

So you can increase stack size for thread using following code:

var stackSize = 10000000;
Thread thread = new Thread(new ThreadStart(BigRecursion), stackSize);

> Thread(ThreadStart, Int32) -- > Initializes a new instance of the > Thread class, specifying the maximum > stack size for the thread.

Source

Hope this what you need.

Solution 2 - C#

I think you are risking problems here. It's hard to determine exactly how much stack a recursive algorithm will use. And, if you are to the point where there's some question about if there'll be enough, I'd look for another approach.

Most recursive algorithms could be rewritten to not be recursive. You can then allocate as much memory as you need and even recover gracefully if there's not enough.

Solution 3 - C#

The default stack size is stored in the PE header.

If you spawn the thread yourself, Thread has a constructor that takes the stack size as a parameter.

However, the default .NET stack size of 1 MB should be enough for most tasks, so before you change it you should at least review the task.

Solution 4 - C#

Even if you manage to get greater recursion depths, simply for performance reasons I would implement this algorithm without recursion. Method calls are way more expensive than iterations within a while loop. I'd strongly advise against implementing anything that requires fiddling with the default stack size.

I occasionally use recursion but only when the call depth is defined and low (as in less than 100). When creating commercial software, using recursive algorithms that have an indefinite number of iterations is completely unprofessional and likely to give you very angry customers.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKeith NicholasView Question on Stackoverflow
Solution 1 - C#Andrew OrsichView Answer on Stackoverflow
Solution 2 - C#Jonathan WoodView Answer on Stackoverflow
Solution 3 - C#Brian RasmussenView Answer on Stackoverflow
Solution 4 - C#MickView Answer on Stackoverflow