WPF Performance & Best Practices

WPF Performance & Best Practices WPF Performance & Best Practices - Start

2016-06-30 152K 152 0 0

WPF Performance & Best Practices - Description

Dirk Primbs, Microsoft Corp.. Agenda. Performance Strategies. WPF architecture: on Threads and Trees. WPF is managed code…. Tips and Tools. Resources. Session . Objectives. & . Takeaways. Session . ID: 383490 Download Presentation

Download Presentation

WPF Performance & Best Practices




Download Presentation - The PPT/PDF document "WPF Performance & Best Practices" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.



Presentations text content in WPF Performance & Best Practices

Slide1

WPF Performance & Best Practices

Dirk Primbs, Microsoft Corp.

Slide2

Agenda

Performance Strategies

WPF architecture: on Threads and Trees

WPF is managed code…

Tips and Tools

Resources

Slide3

Session Objectives & Takeaways

Session

objective

(s):

Provide

a

clear

understanding

of

WPF Performance

Bottlenecks

A

a

brief

background

on

the

graphics

subsystem

and

architecture

of

WPF

Build

for

Performance

from

the

beginning

WPF 3.5 SP 1

contains

many

performance

related

enhancements

Slide4

Performance… First things first

Do

as

much

as

you

need

and

as

little

as

possible

Think in

terms

of

scenario

Don’t push to the limit

Meet

the

customers

expectations

Don‘t

try

to

be

smarter

Slide5

WPF ArchitectureWPF is a Retained Mode Graphics System

Immediate Mode

Examples: OpenGL, DX, GDI, GDI+

Application structure must be managed by user-written code

Often the whole window is redrawn every frame

Otherwise, dirty regions, visible regions, and z-order must all be managed by user code.

Slide6

WPF ArchitectureWPF is a Retained Mode Graphics System

Retained Mode

Examples: HTML, SVG, Win32,

Silverlight

,

Scene graph is managed by graphics system

Dirty Regions are managed by the graphics system

Imagine Notepad with a blinking Cursor

Applications can change individual properties of their scene and the graphics system determines how much needs to be redrawn

Slide7

Retained mode It’s all about Trees…

Visual Tree

Composition Tree

Slide8

Looking at the Visual Tree

demo

Slide9

WPF ArchitectureWPF’s Threading Model

Two threads worth mentioning

UI Thread

PresentationCore.dll, PresentationFramework.dll, WindowsBase.dll, etc…

Managed code

Render/Composition Thread

Was milcore.dll

 N

ow wpfgfx.dll

Unmanaged code

Calls into unmanaged Direct3D

Threads communicate via Channel Protocol

Slide10

Graphics from a Performance standpoint

Slide11

HW acceleration – not always active

Tier 0Tier 1Tier 2DX < 77 <= DX < 9Video RAM >= 30MBPixel Shader >= 1.0Vertex Shader >= 1.0DX >= 9Video RAM >=120 MBPixel Shader >= 2.0Vertex Shader >= 2.0Multitexture units >=4

using System.Windows.Media

RenderCapability.Tier

<< 16

Animation.Storyboard.DesiredFrameRate

Slide12

Optimize for Rendering

There is stuff that will not be accelerated!

Bitmap Effects (note some changes here with SP1)

RenderTargetBitmap

Tilebrush

Operations requires more RAM, then available in video card

Layered windows

Prove carefully if you really need it!

SP1 enables direct access to surfaces &

shaders

Slide13

But most problems are on the UI Thread

Remember

That‘s

where

the

visual

tree

lives

Avoid

Measurements

!

Small

is

beautiful

Move Code

to

another

thread

Virtualize

your

data

Use

static

resources

Slide14

Small is beatifulHow your visual tree becomes smaller…

FrameworkElement

is not base class

Shapes vs. Drawing

Polyline

vs.

StreamGeometry

Not every “control” is control

Each

TextBox

contains 30 elements

Each Label contains 5 elements

Each

TextBlock

contains only one

Slide15

Small is beautiful (2)

Use TextBlock

Or even GlyphRuns directly

TextBlock is 32 times faster then FlowDocument

The less elements you use the better

Slide16

Measurements & Tree WalkThe "real" problem with to many elements

Automatic behavior brings comfort, but it costs…

ScrollViewer

ScrollBarVisibility = Auto

GridLength.Star

,

ResizeMode

,

SizeToContent

Sometimes useful, do not overuse that…

FrameworkElement

Width/Height= Auto

Don’t you know the real size of content? Resize = layout = tree walk

Canvas in the smallest content control – it’s much smaller than Grid

More rows and columns means bigger tree

Custom cell template = more then 60 FrameworkElements

Slide17

Virtualize your data…

Instantiate on demand

VirtualizingStackPanel is 70x faster, than

StackPanel

Treeview

virtualized in SP1

You can virtualize data by yourself

Slide18

Use static resources…

StaticResource vs. DynamicResource

StaticResource = one evaluation

DynamicResource = one reference

Use ResourceDictionary to share resources

Scale your images

Freeze whenever you can

Slide19

Remember? It's .NET

IList vs.

IEnumerable

– Guesses?

XML vs. CLR

Set DataContext instead of XAML and switch it on Application.OnActivated

Slide20

Smart Databinding

DependencyProperty is

x3

faster than INotifyPropertyChanged

ObservableCollection<T> accesses single items 90 times faster than List<T>

ObjectDataProvider is

x20

smaller than XmlDataProvider

Slide21

Perf Tools

Snoop

G

enerally useful to understand your app, view element tree.

WPFPerf

Suite

Perf

“power toy”, a set of diagnostic tools

Visual Studio Profiler

Great for CPU profiling

VS Developer Edition and VS Team Suite

CLR Profiler for

.Net

Shows managed memory usage and leaks

Slide22

Perf ToolsWPF Perf Suite: Perforator

To detect low

perf

b/c SW rendering:

Tint SW rendering:

Draws purple when falling back to SW (or when SW

api

used, old driver, card, layered windows on XP, etc)

# SW Render Targets:

If not 0, significant

perf

problem (old card, layered windows on XP)

# HW Render Targets:

# should be equal to the number of app windows times # of display adapters. Indicates app running in HW

Low

perf

indicators

Large # of Intermediate Render Targets:

additional images that WPF needs in order to get content ready for drawing

Maximum SW/HW IRTs per Frame

:

Shows max # of surfaces needed to render any one frame of the application. Usually caused by the use of

DrawingBrush

,

VisualBrush

, Opacity, or Tile modes on a

TileBrush

. If # high (e.g. > 7), indicates a potential

perf

issue

Slide23

Perf ToolsWPF Perf Suite: Visual Profiler

Inspect the Visual Tree

Show “hot path” of layout time:

Tints the elements in the tree based on their time spent in layout

Shows inclusive/exclusive times and element counts

History graph of time breakdown:

Helps identify whether an application’s bottlenecks lie in layout, rendering, animation, etc

Slide24

Perf ToolsETW Event Trace & Event Trace Viewer

Useful to view low-level WPF ETW events.

WClientUceNotifyPresent

:

Use to calculate frames-per-second rendering

perf

(e.g. during animation, video, etc)

WClientLayout

:

Use to calculate time app spends in laying out controls (e.g. during resize)

Can also use

Xperf

/

Xperfinfo

Slide25

Plan your application performance

Don’t put performance testing to the end

Do prioritize performance in dev. Plan

“Kill ‘

em

when they small”

Plan performance-oriented features

Test on real world hardware

Share your knowledge with designers

Know how things work “under the hoods”

Slide26

Resources

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 Guidance

http://blogs.msdn.com/timothyc/

Windows Presentation Foundation SDK

http://blogs.msdn.com/wpfsdk/

Ian Who – VSTS profiler

http://blogs.msdn.com/ianhu/

Rico

Mariani

– Performance Tidbits

http://blogs.msdn.com/ricom/

Dwayne Need – Presentation Source

http://blogs.msdn.com/dwayneneed/

Slide27

Additional Resources

Optimizing WPF App

Perf

MSDN paper:

http://msdn2.microsoft.com/en-us/library/aa970683.aspx

Snoop tool:

http://www.blois.us/Snoop/

CLR Profiler:

http://www.microsoft.com/downloads/details.aspx?FamilyID=a362781c-3870-43be-8926-862b40aa0cd0&displaylang=en

Binding related blogs:

http://www.beacosta.com/blog/

Various

Perf

related blog

http://blogs.msdn.com/jgoldb

Startup best practices, finding memory leaks, etc

Slide28

In case you want to reach me…

My

Blog (

it‘s

German

though

)

http://blogs.msdn.com/dirkpr

My

twitter

account

http://twitter.com/dirkp_en

Mail

dirkp@microsoft.com

Slide29

Thank

you

!

Slide30

Perf in 3.5 SP1 Graphics

Legacy Blur and

DropShadow

have been accelerated unless they:

Are used in an

EffectGroup

Have too large a blur radius

Aren’t running on a Tier-2 video card

The rest of the legacy Effects have not been accelerated

The legacy extensibility mechanism has not been accelerated

Legacy effects are being marked obsolete

Visual Studio will produce a warning on compilation

Slide31

Perf in 3.5 SP1 Graphics

WriteableBitmap

System memory bitmap

Buffer contents can be programmatically changed

In WPF 3.0 we had a WB implementation

It would allocate a new bitmap with every frame update

WPF 3.5 added

InteropBitmap

No

Perf

/Memory problems

Exhibited tearing

Couldn’t be synchronized with UI changes (e.g. Adorners overlaid on top)

Slide32

Perf in 3.5 SP1 Graphics

Support for user-extensible HW Accelerated Effects

Effect authors write a pixel

shader

in HLSL (

H

igh

L

evel

S

hader

L

anguage), compile it, and pass WPF the compiled HLSL

bytecode

Extensible Effects can expose DP that can be written to, read from, animated and bound just like any other DPs

Full-trust only

Slide33

Perf in 3.5 SP1 Graphics

Improved Text Performance

Improved glyph management infrastructure provides text rendering

perf

gains

Gains mostly noticeable in:

VisualBrushes

,

DrawingBrushes

, Viewport2DVisual3D

Improved Z-index Scenarios

Significantly improved performance of scenarios that continuously modify Z-Index property of Panel elements (e.g. 2D Carrousel)

Slide34

Startup Best Practices

Postpone initializations to after UX is shown Avoid Authenticode (requires many DLL loads + network access)

If you serialize at startup, create serialization helper assemblies (use SGEN tool)

Place strong-name assemblies in GAC (fixed in 3.5 SP1 in most scenarios)

Consider

NGEN’ing

your app

Understand

ClickOnce

impact

Consider setting

ClickOnce

options to version check either:

after

app started (or at time interval) , but

not at before app start

.

Use Splash Screen (easy w/ 3.5 SP1)

See more on our blog (

http://blogs.msdn.com/jgoldb

)

Slide35

Perf Best Practices

Plan for performance:

Understand your main scenarios

Define

perf

goals

Add

perf

tests for your scenarios

Profile & catch

perf

bugs early.

Add richness/features while monitoring

perf

Make performance tuning an iterative process

Slide36

Perf Best Practices

Reduce unnecessary invocations of the layout pass.

Update a Transform rather than replacing it

Use the ‘Most Efficient’ Panel where Possible (e.g. don’t use Grid if you need a Canvas)

Use Drawing which are ‘cheaper’ than Shapes (when possible)

Use

StreamGeometry

which are light-weight alternative to

PathGeometry

for creating geometric shapes.

Use

DrawingVisual

to render shapes, images, or text

If you need thumbnail images, create a reduced-sized version of the image. (by default, WPF loads your image and decodes it to its full size)

Decode the image to desired size and not to the default size.

If possible, combine the images into a single image, such as a film strip composed of multiple images.

Set

BitmapScalingMode

to

LowQuality

for smoother animation when scaling bitmap to

instrcut

WPF to use speed-optimized algorithm

Slide37

Perf Best Practices

Set

CachingHint

when possible - conserves memory

Brush selection is critical to good performance. Don’t use a

VisualBrush

or

DrawingBrush

when an

ImageBrush

or

SolidColorBrush

would be sufficient.

Rendering images is usually faster than rendering vector content. To draw a complex, static vector content (that may need to be repeatedly

rerendered

), consider rendering it into a

RenderTargetBitmap

first and drawing it as an image instead.

Remember to clear Event Handlers to prevent object from remaining alive (see blog)

Remember to

Virtualize

Share resources: If you use custom controls , define control resources at the Application or Window object level, or in the default theme for the custom controls

Share a Brush w/o copying by defining it as a resource

When possible use static Resources vs. Dynamic Resource

Slide38

Perf Best Practices

Don’t use

FlowDocument

element when all you need is a Label or

TextBlock

.

Avoid Binding to

Label.Content

Property, use

TextBlock

instead if source is frequently changes. (String is immutable, so Label’s

ContentPresenter

must regenerate new content)

Binding to XML content is slower than CLR objects. Don’t convert CLR object to XML if the only purpose is binding.

When Brush is used to set the Fill or Stroke of an element, use the Brush...Opacity value rather than element's Opacity property

Hit test on large 3D surfaces is expensive, if possible disable hit test (

IsHitTestVisible

=false)

Slide39

Perf in 3.5 SP1

Container Recycling - improved Scroll

Perf

We keep & reuse the UI elements that go out of view during scrolling

Supported for :

ListView

,

ListBox

,

TreeView

Provide up to 40% scroll performance improvement in the basic case (e.g. elements contain text)

To use set:

<

ListBox

VirtualizingStackPanel.VirtualizationMode

="Recycling

"

/>

Slide40

Perf in 3.5 SP1

Deferred (Non-Live) Scrolling

Perceived

perf

improvement for scrolling.

Content in view is static until scrolling is complete. Similar to Outlook.

You can write app code to display preview thumbnail

To use, set:

<

ListBox

ScrollViewer.IsDeferredScrollingEnabled

= “true”

/>

Slide41

Perf in 3.5 SP1

Virtualized

TreeView

control

Much lower memory consumption

Enables

TreeView

scenarios with large # of elements

To use, set:

<

TreeView

VirtualizingStackPanel.IsVirtualizing

= “true”

/>

Slide42


About DocSlides
DocSlides allows users to easily upload and share presentations, PDF documents, and images.Share your documents with the world , watch,share and upload any time you want. How can you benefit from using DocSlides? DocSlides consists documents from individuals and organizations on topics ranging from technology and business to travel, health, and education. Find and search for what interests you, and learn from people and more. You can also download DocSlides to read or reference later.