I have some code which uses recursion in its implementation. The profiler which I'm using doesn't do well with recursive function calls, so I'd like to rewrite it to be non-recursive.
The current code is something like this:
void Parse(Foo foo)
{
A()
for (;;)
{
B();
if (C())
return;
if (D())
{
Run();
}
E();
}
}
void Run()
{
X();
if (Y())
{
Parse();
}
Z();
}
The above is pseudo-code. The letters A, B, C, D, E, X, Y, and Z are methods, and so are Parse() and Run(). For simplicity I left out various parameters and object dereferences (e.g. Run is a method of an object instance, and it takes some parameters).
Anyway, my question is, how do I turn this into non-recursive code?
The equivalent non-recursive code seems to me to be:
void Parse(Foo foo)
{
//create a local stack variable to emulate recursion
Stack<Foo> foos = new Stack<Foo>();
foos.Add(foo());
start_subroutine:
A()
for (;;)
{
B();
if (C())
{
//instead of returning from a recursive call
if (foos.Count > 1)
{
foo = foos.Pop();
goto end_subroutine;
}
return;
}
if (D())
{
//instead of invoking Run as a subroutine, bring its functionality inline
//Run();
X();
if (Y())
{
//instead of calling self recursively
//Parse();
//push onto a local stack variable and jump
foos.Add(foo);
goto start_subroutine;
}
end_subroutine:
Z();
}
E();
}
}
I'm okay with doing this, but I don't see how to do it without using goto; and I don't remember ever seeing someone write that this is one of the cases when goto is necessary.