Wednesday, February 23, 2011

Performance Tips of WPF

WPF (Windows Presentation Foundation) provides a very easy way to develop rich user experiences. A drop shadow for example can added by inserting two simple lines of XML. But this simplicity can also mislead us to overuse them. This leads to performance issues. The following tips may help you to fix or avoid them.

1. Reduce the number of visuals by removing unneeded elements, combining layout panels and simplifying templates. This keeps the memory footprint small and improves the rendering performance.

2. Lower the framerate of animations by setting Storyboard.DesiredFrameRate to lower the CPU load. The default is 60 frames/second

3. 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.

4. Enable Container Recycling. Virtualization brings a lot of performance improvements, but the containers will be disposed and re created, this is the default. But you can gain more performance by recycle containers by setting VirtualizingStackPanel.VirtualizationMode="Recycling"

5. Disable Assembly localization if you don't need it. By using the [NeutralResourcesLanguageAttribute]. This prevents an expensive lookup for satelite assemblies

6. Dispatch expensive calls either within the UI thread with a lower DispatcherPriority by calling Dispatcher.BeginInvoke() or to a background thread by using a BackgroundWorker to keep the UI responsive.

7. Use StreamGeometries instead of PathGeometries if possible to draw complex 2D geometries, because they are much more efficient and consume less memory.

8. Prevent Software Rendering. The use of transparent windows by setting AllowsTransparency to true or using old BitmapEffects can cause WPF to render the UI in software on Windows XP, which is much slower.

9. Fix binding errors because they consume a lot of time, trying to resolve the path error, including searching for attached properties. You can find them by looking for System.Windows.Data Error in the Visual Studio output log.

10. Freeze Freezables by calling Freeze() in code or PresentationOptions:Freeze="true" in XAML. This reduces memory consumption and improves performance, because the system don't need to monitor for changes.

11. Virtualize lists and views by using a VirtualizingStackPanel as ItemsPanel for lists. This only creates the visible elements at load time. All other elements are lazy created when they get visible. Be aware that grouping or CanContextScrol="True" prevents virtualization!

No comments: