且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何避免更改堆栈大小,并避免让C#中的堆栈溢出

更新时间:2021-12-28 00:16:24

前阵子我探讨了这个问题在我的博客。或者说,我摸索出了相关的问题:你如何找到一个二叉树的深度,而无需使用递归?递归树的深度解决方案是小事,但吹如果树是高度不平衡的堆栈。

A while back I explored this problem in my blog. Or, rather, I explored a related problem: how do you find the depth of a binary tree without using recursion? A recursive tree depth solution is trivial, but blows the stack if the tree is highly imbalanced.

我的建议是研究解决这个简单问题的方式,然后决定哪些其中,如果有的话,可以适应您的稍微复杂的算法。

My recommendation is to study ways of solving this simpler problem, and then decide which of them, if any, could be adapted to your slightly more complex algorithm.

请注意,在这些文章中的例子给出了完全在JScript中。但是,它不应该是很难使之适应于C#。

Note that in these articles the examples are given entirely in JScript. However, it should not be difficult to adapt them to C#.

下面我们开始定义的问题。

Here we start by defining the problem.

的http://博客.msdn.com / ericlippert /存档/ 2005/07/27 /递归部分 - 一个递归数据结构和-functions.aspx

在溶液中的第一次尝试是典型的技术,你可能会采取:定义一个明确的协议栈;使用它,而不是依赖于操作系统和编译器执行堆栈为您服务。这就是当面对这个问题大多数人做的。

The first attempt at a solution is the classic technique that you'll probably adopt: define an explicit stack; use it rather than relying upon the operating system and compiler implementing the stack for you. This is what most people do when faced with this problem.

http://blogs.msdn.com/ericlippert/archive/2005/08/01/recursion-part - 两个 - 展开 - 一个递归函数与 - 一个显式-stack.aspx

与解决方案的问题是,它是有点一团糟。我们可以去更远不是简单地使我们自己的堆栈。我们可以使我们自己的小领域特定的虚拟机都有自己的堆分配栈,然后通过编写一个程序,它针对该机器解决问题!这是比它听起来其实更容易;机器的操作可能会非常高的水平。

The problem with that solution is that it's a bit of a mess. We can go even farther than simply making our own stack. We can make our own little domain-specific virtual machine that has its own heap-allocated stack, and then solve the problem by writing a program that targets that machine! This is actually easier than it sounds; the operations of the machine can be extremely high level.

http://blogs.msdn.com/ericlippert/archive/2005/08/04/recursion-part-three-building-a-dispatch- engine.aspx

最后,如果你真的惩罚一个馋嘴(或编译器的开发者),你可以在继续改写程序传球方式,从而消除了对堆栈的需要在所有的

And finally, if you are really a glutton for punishment (or a compiler developer) you can rewrite your program in Continuation Passing Style, thereby eliminating the need for a stack at all:

http://blogs.msdn.com/ericlippert/archive/2005/08/08/recursion-part-four-continuation-passing-style.aspx

http://blogs.msdn.com/ericlippert/archive/2005/08/11/recursion-part-five-more-on-cps.aspx

HTTP: //blogs.msdn.com/ericlippert/archive/2005/08/15/recursion-part-six-making-cps-work.aspx

CPS是由一群代表之间的关系,其编码移动隐含的堆栈数据结构关闭系统堆栈和到堆上的一个特别聪明的办法。

CPS is a particularly clever way of moving the implicit stack data structure off the system stack and onto the heap by encoding it in the relationships between a bunch of delegates.

下面是我所有的递归文章:

Here are all of my articles on recursion:

http://blogs.msdn.com/ericlippert/archive/tags/Recursion/default.aspx