Tuesday, July 10, 2007 1:45 AM dbottjer

Thoughts On Recursion

Recursion is a computer science concept in which a method / function essentially calls itself until some condition is met.  Recursion can be an elegant solution to some logic problems.  However, I believe there are some potential dangers in using recursion that should carefully be consider.  Recursion is not an impossible concept to grasp it is just one that takes some thought.  The skill level of those maintaining an application should be considered before implementing recursion as it is a more advanced programming concept and could lead to serious performance issues of not implement correctly. 

namespace RecursionTest
{
    class Program
    {
        static void Main(string[] args)
        {
               System.Console.WriteLine(calcFactorial(4));
               System.Console.ReadLine();	
         }


        static int calcFactorial(int n)
        {
            return n * calcFactorial(n - 1);
        }

    }
}

Did you spot the bug in the code above? The code never stops when the factorial is complete resulting in an infinite loop.  To fix the code we need to add a simple constraint or check.

namespace RecursionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(calcFactorial(4));
            Console.ReadLine();
        }


        static int calcFactorial(int n)
        {
            if (n == 1)
            {
                return 1;
            }
            else
            {
                return n * calcFactorial(n - 1);
            }
        }
    }
}
The recursive code above is very clean however as demonstrated it is easy to forget the constraint and introduce an infinite loop. I would also like to point out that from a performance standpoint recursion may not be the best choice.  It is often faster to use a looping structure where possible.  Finally, one must consider the impact recursion has on the managed stack in .NET.  Basically the deeper a thread's stack becomes the more difficult it becomes for the Garbage Collector to determine what should be collected and what is still in use. Filed under: , ,

Comments

No Comments