Forms with Lots of Controls Very Slow

S

ShakeDoctor

Many of my forms have lots of controls on them which have to be initialised
when the form is created. The problem is this really slows down the
application, because the forms are created and destroyed every time I want
to show them.

Would it be better to just create all the forms once at the start of the
application (during some 'loading' screen), and then just call the .Show and
..Hide methods on them as and when I need them? This would slow down the
application quite a bit at the start, but at least it would be just a one
off wait for the user.

If I do this, what events are called when the forms are shown and hidden, so
that I can fill in any data in the controls I want before the forms are
shown?

Or is there a better way...
 
H

Hank

You might consider not destroying the form each time you want to display it.
That way the performance penalty is only experienced once in smaller bits
instead of one huge penalty at the beginning. Slow app load times are bad
anyway, you should strive for your first visible screen in your app to load
fast.

The above method means you will be effectively caching the forms which means
you need a way to retrieve them after you hide them.

The below code snippet is a way to do this. formCacheMap is a Hashtable. You
can build your own form management API around this.

So you call this method like
MyBigForm form = GetCachedForm(typeof(MyBigForm)) as MyBigForm

Then you can put in a public Init() method in each of your forms so they
initialize the way you want them:
MyBigForm form = GetCachedForm(typeof(MyBigForm)) as MyBigForm
form.Init();
form.Show();
previousForm.Hide();

Hope this helps,
Hank

// Returns a cached form, or if form has not been instantiated,
// will instantiate it and then return it.
private static Form GetCachedForm(Type type)
{
Form form = null;
if(formCacheMap.ContainsKey(type))
{
form = (Form)formCacheMap[type];
// exception is thrown if current form has been already been disposed
try
{
form.Text = string.Empty;
}
catch(ObjectDisposedException)
{
form = (Form)Activator.CreateInstance(type);
}
}
else
{
form = (Form)Activator.CreateInstance(type);
// Add newly instantiated form into cache
formCacheMap.Add(type, form);
}
return form;
}
 
D

Daniel Moth

You pretty much have it covered. Caching the forms improves performance at
the expense of the memory (which is the trade off every developer faces when
designing a system). Do you want to spread the performance or do it all at
start-up; it depends on what *you* think is acceptable for your users. For
your other question, look for the (de)activated events to handle loading of
data.

Cheers
Daniel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top