Keith Nicholas
Keith Nicholas

Reputation: 44306

C# Recursion Depth - How Deep can you go

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?

Upvotes: 65

Views: 43246

Answers (4)

Mick
Mick

Reputation: 6864

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.

Upvotes: 6

Andrew Orsich
Andrew Orsich

Reputation: 53695

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.

Upvotes: 62

Jonathan Wood
Jonathan Wood

Reputation: 67283

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.

Upvotes: 25

Brian Rasmussen
Brian Rasmussen

Reputation: 116461

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.

Upvotes: 8

Related Questions