wpf for developers - optimizing your wpf application
TRANSCRIPT
Tamir KhasonSoftware consultermPrest systems
:// . . . / /http blogs microsoft co il blogs tamir
Think in terms of scenarioDon’t push to the limitDo only what you have to do
Set your final goalsTarget customer’s expectationsDon’t try to do things “smarter”
WPF is managed codeDon’t forget about memoryDo as little as possible on startup
WPF is retained systemYou have no pixels, you have a treeMinimize trees, keep changes locally
Dependency Dependency ObjectObject
VisualVisual
UIElementUIElement
Framework Framework ElementElement
ControlControl
ShapeShape
FreezableFreezable
AnimatableAnimatable
DrawingDrawingGeometryGeometry
Style, Resources, Binding, PropertiesStyle, Resources, Binding, Properties
TemplatesTemplates
AnimationAnimation
Transformation, Bounds, ClipTransformation, Bounds, Clip
Input, Focus, Layout, Routed EventsInput, Focus, Layout, Routed Events
Change notifications, multithreadingChange notifications, multithreading
Rendering threadRendering thread – mostly GPU, unmanaged
Part of tree to render, PROBLEMS (which hard to detect)
UI threadUI thread - CPU only, managedAll services, your code, tree, PROBLEMS
Bitmap EffectsRenderTargetBitmapTilebrushOperations requires more RAM, then available in video cardLayered windows
Your code is running hereIt runs in CPU onlyVisual tree is living hereMost of your performance problems are here!
Use smaller Visual TreeDon’t force unnecessary measurementsVirtualize your dataUse static resourcesMove your code into other threadCreate your own other UI threads
FrameworkElement is not base class
Shapes vs. DrawingPolyline vs. StreamGeometry
Not every “control” is controlEach TextBox contains 30 elementsEach Label contains 5 elementsEach TextBlock contains only one
Use TextBlockUse TextFormatterOr even GlyphRuns directlyTextBlock is 32 times faster then FlowDocumentUse fewer elements, everything in WPF have costs
Label = 3 X 5 = 15Label = 3 X 5 = 15
Grid = LayoutGrid = Layout
ViewBox = Layout + ViewBox = Layout + MeasurementsMeasurements
ListBox is too complicated ListBox is too complicated for such layoutfor such layout
VirtualizingStackPanel is VirtualizingStackPanel is 70x faster, then 70x faster, then
StackPanelStackPanel
ScrollViewer ScrollBarVisibility = AutoDon’t calculate nothingDon’t tickle Layout Engine
FrameworkElement Width/Height= AutoDon’t you know the real size of content? Resize = layout = tree walkWhy to measure?
GridLength.Star, ResizeMode, SizeToContentWant dynamic behavior – do it, but not too muchMake sure, it’s absolutely necessary
Canvas in the smallest content control – it much smaller, then Grid
More rows and columns means bigger treeCustom cell template = more then 60 FrameworkElements
Instantiate on demand
VirtualizingStackPanel is 70x faster, then StackPanel
You can virtualize data by yourself
Virtualization does delete and create tree – measure before implementing
StaticResource vs. DynamicResourceStaticResource = one evaluationDynamicResource = one reference
Use ResourceDictionary to share resources
You can Load and Unload resources on demand
Scale your images
Freeze whenever you can
IList vs. IEnumerable
XML vs. CLR
SelectedIndex calls to IndexOf
Set DataContext instead XAML and switch it on Application.OnActivated
DependencyProperty is x3 faster, then INotifyPropertyChanged
ICustomPropertyDescriptor is your friend for vary property set
ObservableCollection<T> is x90 faster accesses single item, then List<T>
ObjectDataProvider is x20 smaller, then XmlDataProvider
<ObjectDataProvider x:Key="cars" ObjectType="{x:Type l:Cars}" IsAsynchronous="True“/>
…<Canvas
DataContext="{StaticResource cars}“>
<Image Width="1024" Height="768" Source="{Binding Path=BigImage,
Mode=OneWay, NotifyOnTargetUpdated=True}"
RenderOptions.CachingHint="Cache" RenderOptions.BitmapScalingMode="LowQuality">
</Canvas>
It’s asynchronousIt’s asynchronous
It applies everywhere It applies everywhere only onceonly once
It’s manual and one wayIt’s manual and one way
And saves a And saves a lot of lot of
unmanaged unmanaged resourcesresources
public class Car : DependencyObject
public static readonly DependencyProperty BigImageProperty; FrameworkPropertyMetadata(
default(BitmapSource),FrameworkPropertyMetadataOptions.None));
public class Cars : ObservableCollection<Car>
Setter is slower, but Setter is slower, but getter is much fastergetter is much faster
This property does not This property does not affects neither affects neither
measurement, nor measurement, nor renderingrendering
It’s much better to add It’s much better to add and remove items and remove items
without regeneration without regeneration controlcontrol
DispatcherOperation oper = Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background, LoadFromXML);
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate(object o)
{ CreateCarNode (o); }, node)
BitmapImage image;image. DecodePixelWidth = 200;image.Freeze();
Invoke time consuming Invoke time consuming operations operations
asynchronously with low asynchronously with low prioritypriority
Invoke recent and fast Invoke recent and fast operations asynchronously operations asynchronously
with low prioritywith low priority
Scale and freeze unmanaged and static Scale and freeze unmanaged and static resourcesresources
ColdStart - After reboot or long period of time
Resources are not presentsSystem calls (registry, disk)
WormStart CLR components are already loadedResources are allocated
Tier 0Tier 0Tier 1Tier 1Tier 2Tier 2DX < 7DX < 77 <= DX < 97 <= DX < 9
Video RAM >= 30MBVideo RAM >= 30MB
Pixel Shader >= 1.0Pixel Shader >= 1.0
Vertex Shader >= 1.0Vertex Shader >= 1.0
DX >= 9DX >= 9
Video RAM >=120 MBVideo RAM >=120 MB
Pixel Shader >= 2.0Pixel Shader >= 2.0
Vertex Shader >= 2.0Vertex Shader >= 2.0
Multitexture units >=4Multitexture units >=4
Tier 0Everything is unaccelerated
Tier 1 (YES)Most 2-D Rendering & 3-D Rasterization
Tier 1 (NO)3D lighting calculations, Color-keyed alpha and Text rendering
Tier 2 (YES)Radial Gradients3-D lighting calculationsText rendering3-D antialiasing (Windows Vista™ only)
Always unaccelerated Bitmap Effects, Printed Content, RenderTargetBitmapTilebrush (Tilemode == Tile), Big SurfacesOperations requires more RAM, then available in video cardLayered windows
0%20%40%60%80%
100%BeforeAfter
99%
1% 0%
Rendering Application
System
61%
4%
35%
Rendering Application
System
Before After
Don’t put performance testing to the endDo prioritize performance in dev. Plan“Kill ‘em when they small”
Plan performance-oriented featuresTest on real world hardwareShare your knowledge with designers
Know how things work “under the hoods”
Just code – Tamir Khasonhttp://blogs.microsoft.co.il/blogs/tamir/
WPF Performance on MSDNhttp://msdn2.microsoft.com/en-us/library/aa970776.aspx
Josh Smith on WPF http://joshsmithonwpf.wordpress.com/
Henry Hahn – WPF Program Managerhttp://blogs.msdn.com/henryh/
Tim Cahill – WPF Performance Guidancehttp://blogs.msdn.com/timothyc/
Windows Presentation Foundation SDKhttp://blogs.msdn.com/wpfsdk/
Ian Who – VSTS profilerhttp://blogs.msdn.com/ianhu/
Rico Mariani – Performance Tidbitshttp://blogs.msdn.com/ricom/
Dwayne Need – Presentation Sourcehttp://blogs.msdn.com/dwayneneed/
? הייתי איך! לדעת מאוד לי חשוב
הקדישו 2בבקשהאת ומלאו דקות
המשוב
© 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.
The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after
the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
t-shirts*