C# 递归深度 - 你能走多深
是否有任何控制可以递归调用某个东西的数量?
从一个基本的测试程序中,我得到了刚刚超过 18k 的递归深度
,这取决于堆栈大小......
有没有办法用大量堆栈设置一块内存(可能是一个线程)来增加递归深度?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
即使您设法获得更大的递归深度,仅仅出于性能原因,我也会在没有递归的情况下实现该算法。方法调用比 while 循环中的迭代要昂贵得多。我强烈建议不要实施任何需要调整默认堆栈大小的内容。
我偶尔会使用递归,但仅当调用深度已定义并且较低时(如小于 100)。在创建商业软件时,使用具有无限迭代次数的递归算法是完全不专业的,并且可能会让您的客户非常生气。
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.
我在某些文档识别过程中增加了堆栈大小。这确实是需要的。
因此,您可以使用以下代码增加线程的堆栈大小:
来源
希望这是您所需要的。
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:
Source
Hope this what you need.
我认为你在这里冒着出现问题的风险。很难准确确定递归算法将使用多少堆栈。而且,如果您对是否足够有疑问,我会寻找另一种方法。
大多数递归算法都可以重写为非递归算法。然后,您可以根据需要分配尽可能多的内存,甚至在内存不足时优雅地恢复。
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.
默认堆栈大小存储在 PE 标头中。
如果您自己生成线程,则 Thread 有一个将堆栈大小作为参数的构造函数。
但是,默认的 .NET 堆栈大小 1 MB 对于大多数任务来说应该足够了,因此在更改它之前,您至少应该检查该任务。
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.