45

NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc. Douglas Boling President

  • View
    230

  • Download
    0

Embed Size (px)

Citation preview

Page 1: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President
Page 2: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

NET Compact Framework 2.0: Optimizing for Performance

NET Compact Framework 2.0: Optimizing for PerformanceDouglas BolingPresidentBoling Consulting Inc.www.bolingconsulting.com

Douglas BolingPresidentBoling Consulting Inc.www.bolingconsulting.com

Page 3: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

AgendaAgenda

General ConceptsStarting upThe garbage collectorMeasuring PerformanceTips and Techniques

General ConceptsStarting upThe garbage collectorMeasuring PerformanceTips and Techniques

Page 4: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Performance… Performance…

…Is important!

This code isn’t on the desktop

Mobile devices are used in real world situationsTime looking at the display is time not looking elsewhere

Bad performance can be dangerous to the user

Embedded devices tend toward time critical jobs

Every task is real time for some measurement of time

…Is important!

This code isn’t on the desktop

Mobile devices are used in real world situationsTime looking at the display is time not looking elsewhere

Bad performance can be dangerous to the user

Embedded devices tend toward time critical jobs

Every task is real time for some measurement of time

Page 5: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

General Performance ConceptsGeneral Performance Concepts

Design in performanceDon’t wait until beta to think about performanceSet performance goals

Less code is faster codeFewer objects are better for performance

Don’t create garbageRecycle and re-use expensive resources

“Perceived” performance is performanceUse threads and async calls Initialize lazily

Understand what the APIs are doing

Design in performanceDon’t wait until beta to think about performanceSet performance goals

Less code is faster codeFewer objects are better for performance

Don’t create garbageRecycle and re-use expensive resources

“Perceived” performance is performanceUse threads and async calls Initialize lazily

Understand what the APIs are doing

Page 6: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

The KeyThe Key

Know the .NET Compact FrameworkThe different versions

How it loads applications

How it JITs code

How it manages objects

How it integrates with the underlying operating system

Know the .NET Compact FrameworkThe different versions

How it loads applications

How it JITs code

How it manages objects

How it integrates with the underlying operating system

Page 7: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Know the .Net Compact FrameworkThe Different Versions

Know the .Net Compact FrameworkThe Different VersionsCompact Framework 1.0

Three service packs

Significant performance improvements for SP2

Bug fixes in SP3

Compact Framework 2.0Significant performance improvements (yet again!)

SP 1 in beta

Compact Framework 1.0Three service packs

Significant performance improvements for SP2

Bug fixes in SP3

Compact Framework 2.0Significant performance improvements (yet again!)

SP 1 in beta

Page 8: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Performance Improvements Performance Improvements

V1 V1 SP2 V2

Method Calls(Calls/sec)

3.7M 8.1M

Virtual Calls(Calls/sec)

2.4M 5.3M

Simple P/Invoke(Calls/sec)

733K 1.7M

Primes (to 1500)(iterations/sec)

562 853

GC Small (8 bytes)(Bytes/sec)

1M 7.5M

GC Array (100 Int’s)(Bytes/sec)

25M 112M

XML Text Reader200KB (seconds)

1.7 1.2 0.72

DataSet (static data) 4 tables, 1000 records (seconds)

13.1 6.6 3.5

DataSet (ReadXml) 3 tables, 100 records (seconds)

12.3 6.5 4.5

Bigger #is better

Smaller #is better

Page 9: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Know the .Net Compact FrameworkApplication Startup

Know the .Net Compact FrameworkApplication StartupStart time is important for first impression

Security checks add time to startupWindows Mobile 5 and Smartphone 2003 perform hash check of all executable files

.Net Compact Framework performs hash check to verify strong name

Keep .exe small, don’t use a strong name on it

For example: avoid embedded resources

Start time is important for first impression

Security checks add time to startupWindows Mobile 5 and Smartphone 2003 perform hash check of all executable files

.Net Compact Framework performs hash check to verify strong name

Keep .exe small, don’t use a strong name on it

For example: avoid embedded resources

Page 10: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Know the .Net Compact FrameworkForm Loading

Know the .Net Compact FrameworkForm LoadingPerformance is ‘perceived’ performance

Preload form classes

Do this asynchronously if loading large amounts of data

Performance is ‘perceived’ performance

Preload form classes

Do this asynchronously if loading large amounts of data

Page 11: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Example: Split Off Big JobsExample: Split Off Big Jobspublic partial class frmAbout : Form{

public frmAbout(){

InitializeComponent();ThreadPool.QueueUserWorkItem(

new WaitCallback(_loadAboutImage));}void _loadAboutImage(object dummy){

string path = …;Image img = new Bitmap(Path.Combine(path,

“yourbitmaphere.bmp"));BeginInvoke(new WaitCallback(_setImage),

new object[] { img });}

}

Page 12: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Know the .Net Compact FrameworkThe just-in-time compiler (“JIT”)

Know the .Net Compact FrameworkThe just-in-time compiler (“JIT”)Designed to be fast and portable, not to

generate optimal code

May pitch JIT-compiled code to conserve memory

Out of memoryWM_HIBERNATE

When application goes to backgroundWM_ACTIVATE

No NGen, install time or persisted code

Designed to be fast and portable, not to generate optimal code

May pitch JIT-compiled code to conserve memory

Out of memoryWM_HIBERNATE

When application goes to backgroundWM_ACTIVATE

No NGen, install time or persisted code

Page 13: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

JITted Code Cost ModelJITted Code Cost Model

Cost model for method callsInstance call: ~2-3x the cost of a native function callVirtual call: ~1.4x the cost of a managed instance callPlatform invoke: ~5x the cost of a managed instance call (marshaling an int parameter)

Watch for hidden method callsProperties are callsforeach generates virtual method calls on collection

for faster than foreach

Cost model for method callsInstance call: ~2-3x the cost of a native function callVirtual call: ~1.4x the cost of a managed instance callPlatform invoke: ~5x the cost of a managed instance call (marshaling an int parameter)

Watch for hidden method callsProperties are callsforeach generates virtual method calls on collection

for faster than foreach

Page 14: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Tips and TricksMathTips and TricksMath

32-bit integers: similar to native

64-bit integers: 5-10x slowerOnly use registers for 32-bit values

Floating point: similar to native for ARMARM processors do not have FPU

32-bit integers: similar to native

64-bit integers: 5-10x slowerOnly use registers for 32-bit values

Floating point: similar to native for ARMARM processors do not have FPU

Page 15: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Tips and TricksCollectionsTips and TricksCollections

Pre-size, resizing creates garbage and copies

foreach has virtual method call overhead, use indexer in tight loops if possible

Pre-size, resizing creates garbage and copies

foreach has virtual method call overhead, use indexer in tight loops if possiblecallvirt instance class IEnumerator::GetEnumerator()...callvirt instance object IEnumerator::get_Current()...callvirt instance bool IEnumerator::MoveNext()callvirt instance bool IEnumerator::MoveNext()

Collections are usually performance sensitiveTest and tweak for optimal performance

Many options: custom collections (for example, based on strongly-typed array), Generic collections, built-in collections, etc.

Collections are usually performance sensitiveTest and tweak for optimal performance

Many options: custom collections (for example, based on strongly-typed array), Generic collections, built-in collections, etc.

Page 16: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

ExceptionsExceptions

Exceptions are cheap…until you throwOnly throw exceptions in exceptional circumstances

Do not use exceptions for control flow

Use performance counters to track the number of exceptions thrown

Replace “On Error/Goto” with “Try/Catch/Finally” in Microsoft Visual Basic®.NET

Exceptions are cheap…until you throwOnly throw exceptions in exceptional circumstances

Do not use exceptions for control flow

Use performance counters to track the number of exceptions thrown

Replace “On Error/Goto” with “Try/Catch/Finally” in Microsoft Visual Basic®.NET

Page 17: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Tips and TricksInteropTips and TricksInterop

Keep in mind the cost of P/Invoke (~5x managed invoke)

Make “chunky” calls, not “chatty” ones

COM Interop VTable calls use P/Invoke path

Avoid IDispatch if possible (~5x slower than VTable)

Watch out for complex marshallingValue types are “blittable”, marshaled quickly

Complex types, including many COM types (e.g. VARIANT, BSTR, SAFEARRAY) are slower

Use [in] [out] attributes to eliminate unnecessary marshalling

Keep in mind the cost of P/Invoke (~5x managed invoke)

Make “chunky” calls, not “chatty” ones

COM Interop VTable calls use P/Invoke path

Avoid IDispatch if possible (~5x slower than VTable)

Watch out for complex marshallingValue types are “blittable”, marshaled quickly

Complex types, including many COM types (e.g. VARIANT, BSTR, SAFEARRAY) are slower

Use [in] [out] attributes to eliminate unnecessary marshalling

Page 18: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Tips and TricksDataTips and TricksData

DataSet.ReadXml—use a schema!

SQL readers/writers are much faster than XML

Use Visual Studio designers and typed data sets

Use SqlCeResultSet

http://blogs.msdn.com/sriram/archive/2005/11/12/492070.aspx

Use DataGrid binding, especially for large DataSets

DataSet.ReadXml—use a schema!

SQL readers/writers are much faster than XML

Use Visual Studio designers and typed data sets

Use SqlCeResultSet

http://blogs.msdn.com/sriram/archive/2005/11/12/492070.aspx

Use DataGrid binding, especially for large DataSets

Page 19: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Tips and TricksData and Web servicesTips and TricksData and Web services

DataSets over Web services is okay in moderation

Send changes only: DataSet.GetChanges() (New in v2)

May require extra work to ensure both sides are in sync

In some cases, it may be better to define your own message format to send data

DataSets over Web services is okay in moderation

Send changes only: DataSet.GetChanges() (New in v2)

May require extra work to ensure both sides are in sync

In some cases, it may be better to define your own message format to send data

Page 20: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Tips and TricksNetworking 101Tips and TricksNetworking 101

Understand the cost of sending dataTime: more layers = more work

Efficiency: more layers = more metadata

Understand the cost of sending dataTime: more layers = more work

Efficiency: more layers = more metadata

Web Services and Web Services and XMLXML

SocketsSockets

HTTPHTTP

Easiest to program and maintain

Least overhead, fastest

Page 21: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Tips and TricksNetworkingTips and TricksNetworking

For most applications, managed sockets should be fast enough and not the limiting factor

http://blogs.msdn.com/mikezintel/archive/2005/03/30/403941.aspx

Do not use synchronous network calls in the GUI thread

Avoid automatically retrying network requests in case of failure

User will generally know if a retry is appropriate; retries can make application appear sluggish

http://blogs.msdn.com/oldnewthing/archive/2005/11/07/489807.aspx

For most applications, managed sockets should be fast enough and not the limiting factor

http://blogs.msdn.com/mikezintel/archive/2005/03/30/403941.aspx

Do not use synchronous network calls in the GUI thread

Avoid automatically retrying network requests in case of failure

User will generally know if a retry is appropriate; retries can make application appear sluggish

http://blogs.msdn.com/oldnewthing/archive/2005/11/07/489807.aspx

Page 22: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

ReflectionReflection

Reflection can be expensive

Performance costType comparisons (typeof())—inexpensive

Member access (Type.InvokeMember())— think10-100x slower

Working set costMember enumerations (Type.GetFields())—expensive

Runtime data structures: ~100 bytes/type, ~80 bytes/method

Be aware of APIs that use reflection as a side effect

Override Object.ToString()

Override GetHashCode() and Equals() for value types

Reflection can be expensive

Performance costType comparisons (typeof())—inexpensive

Member access (Type.InvokeMember())— think10-100x slower

Working set costMember enumerations (Type.GetFields())—expensive

Runtime data structures: ~100 bytes/type, ~80 bytes/method

Be aware of APIs that use reflection as a side effect

Override Object.ToString()

Override GetHashCode() and Equals() for value types

Page 23: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Reflection behind the ScenesReflection behind the Scenes

Pay reflection cost oncePersist objects that use reflection

Web servicesReflect over proxy code when service is created

Reflect over method parameters on first call

XML serializersReflect over type when serializer created

Use GetValue/SetValue to query and populate object

Consider custom serialization if performance critical

Pay reflection cost oncePersist objects that use reflection

Web servicesReflect over proxy code when service is created

Reflect over method parameters on first call

XML serializersReflect over type when serializer created

Use GetValue/SetValue to query and populate object

Consider custom serialization if performance critical

Page 24: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Know the .Net Compact FrameworkThe Garbage Collector (GC)

Know the .Net Compact FrameworkThe Garbage Collector (GC)What triggers a GC?

Memory allocation failure1M GC objects allocatedApplication going to the backgroundGC.Collect (try to avoid!)http://blogs.msdn.com/scottholden/archive/2004/12/28/339733.aspx

What happens at GC time?Freezes all managed threadsFinds all reachable objects and marks themUnmarked objects are freed and added to finalizer queueGC pools may be compactedMemory is returned to OS

What triggers a GC?Memory allocation failure1M GC objects allocatedApplication going to the backgroundGC.Collect (try to avoid!)http://blogs.msdn.com/scottholden/archive/2004/12/28/339733.aspx

What happens at GC time?Freezes all managed threadsFinds all reachable objects and marks themUnmarked objects are freed and added to finalizer queueGC pools may be compactedMemory is returned to OS

Page 25: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

GC Cost ModelGC Cost Model

GC only impacts performance when it runsPrevent it from running too often: don’t create garbage

Test and tune to achieve best balance

Some features have side effects that can create a lot of garbage

String manipulations

Boxing value types

Use performance counters to monitor the GC

GC only impacts performance when it runsPrevent it from running too often: don’t create garbage

Test and tune to achieve best balance

Some features have side effects that can create a lot of garbage

String manipulations

Boxing value types

Use performance counters to monitor the GC

Page 26: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Where does garbage come from?Where does garbage come from?

Unnecessary string copiesStrings are immutable

String manipulations (Concat(), etc.) cause copies

Use StringBuilder

Unnecessary string copiesStrings are immutable

String manipulations (Concat(), etc.) cause copies

Use StringBuilder

String result = "";

for (int i=0; i<10000; i++)

{

result +=

".NET Compact Framework";

result += " Rocks!";

}

StringBuilder result =

new StringBuilder();

for (int i=0; i<10000; i++)

{

result.Append(".NET Compact

Framework");

result.Append(" Rocks!");

}

Page 27: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Where does garbage come from?Where does garbage come from?

Unnecessary boxingValue types are allocated on the stack (fast to allocate)

Boxing causes a heap allocation and copy

Use strongly typed arrays and collectionsNon-generic collections are not strongly typed

Unnecessary boxingValue types are allocated on the stack (fast to allocate)

Boxing causes a heap allocation and copy

Use strongly typed arrays and collectionsNon-generic collections are not strongly typed

class Hashtable {class Hashtable {struct bucket {struct bucket {

Object key;Object key;Object val;Object val;

} } bucket[] buckets;bucket[] buckets;public public ObjectObject this[Object keyObject key] { get; set; }] { get; set; }

}}

Page 28: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

GC Cost ModelSample code: value types and boxingGC Cost ModelSample code: value types and boxing

ArrayList a1 = ArrayList a1 = new ArrayList(100000);new ArrayList(100000);

ArrayList a2 =ArrayList a2 = new ArrayList(100000);new ArrayList(100000);

for (int i = 0; i < 100000; i++) { a1.Add(i * i);}

for (int i = 0; i < 100000; i++) { int j = (int)a1[i]; a2.Add(j);}

int[] ht = new int[100000];int[] al = new int[100000];

for (int i = 0; i < 100000; i++) { ht[i] = i * i;}

for (int i = 0; i < 100000; i++) { int j = ht[i]; al[i] = j;}

546 ms546 ms

Boxed value types Boxed value types 200005200005Managed objs allocated Managed objs allocated 200729200729Garbage Collections (GC) Garbage Collections (GC) 3 3Bytes Collected By GC Bytes Collected By GC 41324132GC Latency Time GC Latency Time 155 ms155 ms

22 ms22 ms

Boxed value types Boxed value types 5 5Managed objs allocated Managed objs allocated 726 726Garbage Collections (GC) Garbage Collections (GC) 0 0Bytes Collected By GC Bytes Collected By GC 0 0GC Latency Time GC Latency Time 0 ms 0 ms

Page 29: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Using GenericsUsing Generics

Can avoid boxing using genericsUnderstand the tradeoffs:

ProsStrongly typed

No unnecessary boxing and type casts

Specialized code is more efficient than shared

ConsInternal runtime data structures and JIT-compiled code aren’t sharedList<int>, List<string>, List<MyType>

May not be faster: make sure to test and measure

Can avoid boxing using genericsUnderstand the tradeoffs:

ProsStrongly typed

No unnecessary boxing and type casts

Specialized code is more efficient than shared

ConsInternal runtime data structures and JIT-compiled code aren’t sharedList<int>, List<string>, List<MyType>

May not be faster: make sure to test and measure

Page 30: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

GC Cost ModelSample code: genericsGC Cost ModelSample code: generics

ArrayList a1 = ArrayList a1 = new ArrayList(100000);new ArrayList(100000);

ArrayList a2 =ArrayList a2 = new ArrayList(100000);new ArrayList(100000);

for (int i = 0; i < 100000; i++) { ht.Add(i * i);}

for (int i = 0; i < 100000; i++) { int j = (int)ht[i]; al.Add(j);}

List<int> ht = new List<int>(100000);List<int> al = new List<int>(100000);

for (int i = 0; i < 100000; i++) { ht.Add(i * i);}

for (int i = 0; i < 100000; i++) { int j = ht[i]; al.Add(j);}

546 ms546 ms

Boxed value types Boxed value types 200005200005Managed objs allocated Managed objs allocated 200729200729Garbage Collections (GC) Garbage Collections (GC) 3 3Bytes Collected By GC Bytes Collected By GC 41324132GC Latency Time GC Latency Time 155 ms155 ms

77 ms77 ms

Boxed value types Boxed value types 5 5Managed objs allocated Managed objs allocated 732 732Garbage Collections (GC) Garbage Collections (GC) 0 0Bytes Collected By GC Bytes Collected By GC 0 0GC Latency Time GC Latency Time 0 ms 0 ms

Page 31: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

FinalizersThe object is dead, long live the object!FinalizersThe object is dead, long live the object!

Cost:Non-deterministic cleanup: unmanaged resources may stay around longer than wantedExtends object lifetime: managed memory is not freed until after finalizer runsCan saturate finalizer thread if create objects faster than they can be finalized

Only use a finalizer if your object contains an unmanaged resource

Implement the “Dispose” pattern (IDisposable)

http://blogs.msdn.com/ricom/archive/2004/05/19/135332.aspx

Cost:Non-deterministic cleanup: unmanaged resources may stay around longer than wantedExtends object lifetime: managed memory is not freed until after finalizer runsCan saturate finalizer thread if create objects faster than they can be finalized

Only use a finalizer if your object contains an unmanaged resource

Implement the “Dispose” pattern (IDisposable)

http://blogs.msdn.com/ricom/archive/2004/05/19/135332.aspx

Page 32: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Sample Code: Finalizer and DisposeSample Code: Finalizer and Dispose

class SerialPort : IDisposable {class SerialPort : IDisposable { IntPtr SerialPortHandle;IntPtr SerialPortHandle;

public SerialPort(String name) {public SerialPort(String name) { // P/Invoke to native code to open serial port// P/Invoke to native code to open serial port SerialPortHandle = SerialOpen(name);SerialPortHandle = SerialOpen(name); }}

~SerialPort() {~SerialPort() { // P/Invoke to native code to close serial port// P/Invoke to native code to close serial port SerialClose(SerialPortHandle);SerialClose(SerialPortHandle); }}

public void Dispose() {public void Dispose() { // P/Invoke to native code to close serial port// P/Invoke to native code to close serial port SerialClose(SerialPortHandle);SerialClose(SerialPortHandle); GC.SuppressFinalize(this);GC.SuppressFinalize(this); }}}}

Page 33: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Know the .Net Compact FrameworkKnow the system

Know the .Net Compact FrameworkKnow the systemIts still Windows

The message loop is hidden, but it’s thereDon’t spend too much time in an event handler

It’s still Windows CEUntil Windows CE 6, you’re limited to a 32M VMYou may run out of VM space before RAMLoad native DLLs early

Otherwise the managed heap will take the entire VM

Its still a small, low cost deviceSystem Performance is data bound

Its still Windows The message loop is hidden, but it’s there

Don’t spend too much time in an event handler

It’s still Windows CEUntil Windows CE 6, you’re limited to a 32M VMYou may run out of VM space before RAMLoad native DLLs early

Otherwise the managed heap will take the entire VM

Its still a small, low cost deviceSystem Performance is data bound

Page 34: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Tips and TricksWindows FormsTips and TricksWindows Forms

Use BeginUpdate/EndUpdate when available

Use SuspendLayout/ResumeLayout when repositioning controls

Keep event handling code tightProcess costly operations asynchronously

Blocking in event handlers will affect UI responsiveness

Limit the work done when a Form loads

Use BeginUpdate/EndUpdate when available

Use SuspendLayout/ResumeLayout when repositioning controls

Keep event handling code tightProcess costly operations asynchronously

Blocking in event handlers will affect UI responsiveness

Limit the work done when a Form loads

Page 35: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Tips and TricksSystem.IOTips and TricksSystem.IO

When using a StreamReader, use buffers that match the internal buffer of the stream

Be aware of the default sizes of internal buffers

FileStream: 128 bytes

StreamReader, StreamWriter: 1024

Avoid Stream.SeekIf must use, use small buffers

When using a StreamReader, use buffers that match the internal buffer of the stream

Be aware of the default sizes of internal buffers

FileStream: 128 bytes

StreamReader, StreamWriter: 1024

Avoid Stream.SeekIf must use, use small buffers

Page 36: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Tips and TricksKnow the target deviceTips and TricksKnow the target device

Windows Mobile 5 devices are noticeably slower than earlier systems

Persistent store

Security checks

Test on all expected target devicesAnd those you don’t expect

Plan for the future Never assume screen sizes or shapes

Smartphone vs. Pocket PC differences

Windows Mobile 5 devices are noticeably slower than earlier systems

Persistent store

Security checks

Test on all expected target devicesAnd those you don’t expect

Plan for the future Never assume screen sizes or shapes

Smartphone vs. Pocket PC differences

Page 37: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Tips and TricksMotherhoodTips and TricksMotherhood

Design, design, design. Weed out problems before they happen

Test, test, test. Keep your eye on performance targets

Just because you can doesn’t mean you should!

Tips and tricks are guidelines for better designs and better habits

Design, design, design. Weed out problems before they happen

Test, test, test. Keep your eye on performance targets

Just because you can doesn’t mean you should!

Tips and tricks are guidelines for better designs and better habits

Page 38: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Tips and TricksMeasuring performanceTips and TricksMeasuring performance

Use Environment.TickCount to measureMeasure times greater than 1 secondStart from known stateEnsure nothing else is runningMeasure multiple times, take averageRun each test in its own AppDomain/ProcessLog results at the endUnderstand JIT-time versus runtime costs

Use Environment.TickCount to measureMeasure times greater than 1 secondStart from known stateEnsure nothing else is runningMeasure multiple times, take averageRun each test in its own AppDomain/ProcessLog results at the endUnderstand JIT-time versus runtime costs

Page 39: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Measuring PerformanceMeasuring Performance

Performance countersCounters give us insight into performance and memory use

Static: <My App>.statHKLM\SOFTWARE\Microsoft\.NETCompactFramework\PerfMonitorCounters (DWORD) = 1

Dynamic: Use NetCFRPM (formerly “TuneIn”)

Performance and working set are closely related

Performance countersCounters give us insight into performance and memory use

Static: <My App>.statHKLM\SOFTWARE\Microsoft\.NETCompactFramework\PerfMonitorCounters (DWORD) = 1

Dynamic: Use NetCFRPM (formerly “TuneIn”)

Performance and working set are closely related

Page 40: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Performance Counters: .stat FilePerformance Counters: .stat Filecounter total last datum n mean min max

Total Program Run Time (ms) 55937 - - - - -App Domains Created 18 - - - - -App Domains Unloaded 18 - - - - -Assemblies Loaded 323 - - - - -Classes Loaded 18852 - - - - -Methods Loaded 37353 - - - - -Closed Types Loaded 730 - - - - -Closed Types Loaded per Definition 730 8 385 1 1 8Open Types Loaded 78 - - - - -Closed Methods Loaded 46 - - - - -Closed Methods Loaded per Definition 46 1 40 1 1 2Open Methods Loaded 0 - - - - -Threads in Thread Pool - 0 6 1 0 3Pending Timers - 0 93 0 0 1Scheduled Timers 46 - - - - -Timers Delayed by Thread Pool Limit 0 - - - - -Work Items Queued 46 - - - - -Uncontested Monitor.Enter Calls 57240 - - - - -Contested Monitor.Enter Calls 0 - - - - -Peak Bytes Allocated (native + managed) 4024363 - - - - -Managed Objects Allocated 1015100 - - - - -Managed Bytes Allocated 37291444 28 1015100 36 8 55588Managed String Objects Allocated 112108 - - - - -Bytes of String Objects Allocated 4596658 - - - - -Garbage Collections (GC) 33 - - - - -Bytes Collected By GC 25573036 41592 33 774940 41592 1096328Managed Bytes In Use After GC - 23528 33 259414 23176 924612Total Bytes In Use After GC - 3091342 33 2954574 1833928 3988607GC Compactions 17 - - - - -Code Pitchings 6 - - - - -Calls to GC.Collect 0 - - - - -GC Latency Time (ms) 279 16 33 8 0 31Pinned Objects 156 - - - - -Objects Moved by Compactor 73760 - - - - -Objects Not Moved by Compactor 11811 - - - - -Objects Finalized 6383 - - - - -Boxed Value Types 350829 - - - - -Process Heap - 1626 430814 511970 952 962130Short Term Heap - 0 178228 718 0 21532JIT Heap - 0 88135 357796 0 651663App Domain Heap - 0 741720 647240 0 833370GC Heap - 0 376 855105 0 2097152Native Bytes Jitted 7202214 152 26910 267 80 5448Methods Jitted 26910 - - - - -Bytes Pitched 1673873 0 7047 237 0 5448

Peak Bytes Allocated (native + Peak Bytes Allocated (native + managed)managed)JIT HeapJIT HeapApp Domain HeapApp Domain HeapGC HeapGC Heap

Garbage Collections (GC)Garbage Collections (GC)

GC Latency Time (ms)GC Latency Time (ms)

Boxed Value TypesBoxed Value Types

Managed String Objects AllocatedManaged String Objects Allocated

Page 41: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Remote Performance MonitorFormally “TuneIn”Remote Performance MonitorFormally “TuneIn”

Supported in .NET CF 2.0 SP1Beta available now

Dynamically uploads performance dataCounters give us insight into performance and memory use

Counters can be exported to PerfMon

Supported in .NET CF 2.0 SP1Beta available now

Dynamically uploads performance dataCounters give us insight into performance and memory use

Counters can be exported to PerfMon

Page 42: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

SummarySummary

Make performance a design requirement and measure

Understanding .Net Compact Framework guides good design

Watch memory usage

Understand APIs and side effects

Develop good design and programming habits with tips and tricks

Make performance a design requirement and measure

Understanding .Net Compact Framework guides good design

Watch memory usage

Understand APIs and side effects

Develop good design and programming habits with tips and tricks

Page 43: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

ResourcesResources

http://blogs.msdn.com/netcfteam/archive/2005/05/04/414820.aspx

.NET Compact Framework version 2.0 Performance and Working Set FAQ

http://blogs.msdn.com/mikezintel/archive/2004/12/08/278153.aspx

.NET Compact Framework Advanced Memory Management

http://blogs.msdn.com/davidklinems/archive/2005/12/09/502125.aspx

Monitoring Application Performance on the .NET Compact Framework

http://blogs.msdn.com/romanbat/archive/2005/01/06/348114.aspx

Generics in the .NET Compact Framework

http://blogs.msdn.com/mikezintel/archive/2005/03/30/403941.aspx

.NET Compact Framework Network Performance

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetcomp/html/netcfperf.asp

Developing Well Performing .NET Compact Framework Applications

Page 44: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

Stop by the MED Content Publishing Team Station in the Microsoft Stop by the MED Content Publishing Team Station in the Microsoft Pavilion or visit the MED Content Publishing Team Wiki site:Pavilion or visit the MED Content Publishing Team Wiki site:http://msdn.microsoft.com/mobility/wiki

ResourcesResources

Need developer resources on this subject? Need developer resources on this subject?

Page 45: NET Compact Framework 2.0: Optimizing for Performance Douglas Boling President Boling Consulting Inc.  Douglas Boling President

© 2006 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.