I’ve been using the popular MVVM Light toolkit: here for creating my Windows Phone applications and had a question regarding the pattern. For every page created, we create a new view model to keep the code behind clean and promote separation of concerns. However The ViewModelLocator’s constructor contains an instantiation of each and every viewmodel.
The ViewModelLocator’s constructor typically looks like this:
public ViewModelLocator()
{
////if (ViewModelBase.IsInDesignModeStatic)
////{
//// // Create design time view models
////}
////else
////{
//// // Create run time view models
////}
CreateMain();
CreatePage2();
CreatePage3();
CreatePage4();
}
If an application contains a bunch of pages, won’t instantiating every ViewModel even for those views that might never be required cause a performance concern?
Am I missing something here?
With any overhead or any concern about performance, it’s a good idea to measure what the overhead/problem is.
It’s true that when coding WP7 through .Net, C#, Silverlight, XAML, DataBinding and MVVMLight then you inserting a lot of “overhead” – and most of that overhead is there for the convenience of the coder, not for the benefit of the user.
However, the WP7 CPU, the video co-processor, the fast RAM and fast SolidState memory are all really quite quick – so there is room for some overhead, and you can use those frameworks to create delightful, responsive WP7 apps.
By all means worry about performance – but its best to drive those concerns through measurement to find out where you need to optimise, or where you need to hide the slowness behind some other UI feature.
Generally when I measure, I find that my performance bottlenecks aren’t where I expect… I also discover that there are always trade-offs – e.g. in your concern here, the tradeoff might be that while the Locator construction code runs slower, the later lookup code can run quicker – so in-app navigation can be faster at the expense of slightly a marginally slower startup time.