An Alternitive to Recursion

I am sure you are aware of the many drawbacks to using a recursive function.  Recursive functions are resource intensive slow and in many cases unreliable.  I would like to provide a very simple alternative to creating a recursive function in c#.

Consider the following recursive code:

private void main()
{

ScanDir(string “”);

}

private void ScanDir(string theDirectory)
{

//Some type of directory scanning code here that fills xDir with a directory name if the file is a directory

if(xDir != “”){
ScanDir(xDir); //  Here ScanDir calls itself again creating a recursive call
}

}

Now we simple need to use a c# stack to avoid recurssion.  As you can see the the following example, very few lines of code were changed and very few were added.  These simple changes make the program far more efficient.

using System.Collections; // you will need this include to use Stacks
Stack dirStack = new Stack(500); // declare a stack to use later

private void main()
{

ScanDir(“.”);

while (dirStack.Count > 0)
{
ScanDir((string)dirStack.Pop());
}

}

private void ScanDir(string theDirectory)
{

//Some type of directory scanning code here that fills xDir with a directory name if the file is a directory

if(xDir != “”){
dirStack.Push(xDir); // push the directory onto the stack for later scanning
}

}

Robbalman

Leave a Reply