tags:

views:

23

answers:

1

Hi all, My application has a navigation framework where each data entry screen is implemented as a usercontrol. Some of these UserControls are very large, and on slow systems can take a few seconds to construct.

In an attempt to speed things up, I'm considering caching these control instances instead of instantiating them each time I need them. In tests, this definitely seems to speed things up.

Very simplified, I'm essentially doing something like this:


public void Navigate(Type pageType)
{
    Control page = GetOrCreatePage(pageType);
    hostPanel.Clear();
    hostPanel.Add(page);
}

private Control GetOrCreate(Type controlType)
{
    if(!cache.Contains(controlType))
        cache.Add(controlType, Activator.CreateInstance(type);    
    return cache[type];
}

My question is - should I be doing this? I'm only asking because I don't see many examples of this, and I've had to do a fair amount or refactoring and rethinking to support the control instances hanging around (managing disposal, event subscriptions, etc). I guess it just feels different so I want to make sure this is OK and I'm not stepping in something I'll smell later...

any feedback is appreciated.

A: 

I would consider why the instances take so long to create, most probably it's because there's some data that takes time to load and it would probably be a better idea to cache that data instead.

Patrik Hägne
Thanks for the reply Patrik. There isn't any IO occurring in the constructor, just UI initialization logic - mostly designer-generated. There really is a bunch of UI on this control.There are, however, some other custom controls hosted in this usercontrol – perhaps they have some inefficient code in their construction or initialization. I'll run this through a profiler to make sure.But if my profiling reveals that everything is ok, and that it’s just the sheer amount of initialization code running, do you see any technical issue with what I'm doing?