Naveen's Weblog

Bridge to future

Get all controls on a windows form without recursion

Posted by codingsense on July 22, 2010


Its given in microsoft patterns and practices to consider replacing recursion with looping because each recursive call adds data to the stack. Examine your code and see if your recursive calls can be converted to a looping equivalent.

I was wondering if all the solutions that uses recursion can be replaced without using recursion.
So I took the first step in looking into my project and found a piece of code that was using recursion, a function that would give me all the controls on a windows form. So I decided trying to convert that code without the use of recursive call.

Here is what I came up with,

static IList getControls(Control ParentControl)
List<Control> ListOfControls = new List<Control>();
List<Control> ContainerControls = new List<Control>();

while (ContainerControls.Count > 0)
foreach (Control control in ContainerControls[0].Controls)
if (control.Controls.Count > 0)
return ListOfControls;

Great, the method gave me proper result as compared with the recursive function, what next I wanted to see how it has increased in performance and I used stopwatch to determine the time taken by both of the methods on the same form which was heavily loaded with controls and containers, it had 82 controls on it. The time taken by recursive function was double the time taken by the new method.

So I concluded that replacing recursive method with looping will enhance performance and also helps in consuming less memory.

If you get a better way to overcome recursion then please feel free to comment, till then I will continue my search for more recursive calls in my code.

Happy Learning 🙂


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: