C# Recursion Depth - How Deep can you go

前端 未结 4 1963
猫巷女王i
猫巷女王i 2020-11-30 06:44

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 sta

相关标签:
4条回答
  • 2020-11-30 06:53

    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.

    0 讨论(0)
  • 2020-11-30 06:54

    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.

    0 讨论(0)
  • 2020-11-30 07:04

    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.

    0 讨论(0)
  • 2020-11-30 07:07

    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.

    0 讨论(0)
提交回复
热议问题