I’ve just read a post of Christian Mosers listing “Top 10 WPF Performance Tips”. I agree with most of them, as they are general tips, but except for one:
“Load resources when needed. Even thow it’s the most comfortable way to merge all resources on application level it can also cost performance by loading all resources at startup. A better approach is to load only often used resources and load the other on view level”
Resources in WPF are lazy load and shared by default. If you place a resource in the application resources from XAML or from any other XAML resources it won’t be loaded until someone reference it using StaticResource or DynamicResource (there are other ways too).
To demonstrate that, I’ve created a very simple application, defines three types: A simple CLR class, a Freezable one and DependecyObject. I’ve created an instance of each one of these types inside the App.xaml resource dictionary. Each type logs a message from within the constructor. Running the application which by default displays the MainWindow you may notice that no instance has been created.
I’ve added four test cases: The first one instantiates a window which uses the Simple class resource, the second uses the Freezable and the third the DependecyObject. Each test case invokes only the relevant resource and results in only one instance, no matter how many windows where created. what’s the type of it. The fourth test case creates a Window which uses the Simple resource but with the x:Shared=”False” XAML parser attribute. This prevents resource sharing.
From that you can learn that:
- Resources in WPF are lazy load. They are loaded only when you reference them.
- Resources in WPF are shared by default like singleton objects.
- You can prevent a resource from being shared by using the x:Shared=”False” XAML attribute.
You can download the tester from here.