39
DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Brian A. Randell Senior Consultant Senior Consultant MCW Technologies, LLC MCW Technologies, LLC

DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Embed Size (px)

Citation preview

Page 1: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

DEV340 Visual BasicTips and Tricks for Optimizing Your Applications

DEV340 Visual BasicTips and Tricks for Optimizing Your Applications

Brian A. RandellBrian A. RandellSenior ConsultantSenior ConsultantMCW Technologies, LLCMCW Technologies, LLC

Page 2: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Me.AboutMe.About

Senior Consultant with MCW Senior Consultant with MCW TechnologiesTechnologies

A Microsoft Certified PartnerA Microsoft Certified Partner

www.mcwtech.comwww.mcwtech.com

Co-author Effective Visual BasicCo-author Effective Visual BasicISBN: 0201704765ISBN: 0201704765

Blog Blog http://sqljunkies.com/WebLog/brianr/http://sqljunkies.com/WebLog/brianr/

Page 3: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Thanks toThanks to

Paul VickPaul VickDevelopment Lead, CompilerDevelopment Lead, CompilerVisual BasicVisual BasicMicrosoft CorporationMicrosoft Corporation

Mahesh PrakriyaMahesh PrakriyaLead Program ManagerLead Program ManagerCommon Language RuntimeCommon Language RuntimeMicrosoft CorporationMicrosoft Corporation

They wrote most of this talk.They wrote most of this talk.

Page 4: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

OutlineOutline

IntroductionIntroduction

Tips and tricks forTips and tricks forAll applicationsAll applications

Windows Forms applicationsWindows Forms applications

ASP.NET applicationsASP.NET applications

Tools/ResourcesTools/Resources

Page 5: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

RememberRemember

There are three kinds of lies: There are three kinds of lies: lies, lies, damn lies, damn lies, and statisticsand statistics..Benjamin DisraeliBenjamin DisraeliPrime Minister of the British EmpirePrime Minister of the British Empire1874-18801874-1880

Page 6: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

IntroductionIntroduction

VB.NET and Visual Basic 6.0VB.NET and Visual Basic 6.0Different platforms, different performanceDifferent platforms, different performance

.NET is a great platform for performance.NET is a great platform for performance

Just don’t make assumptions!Just don’t make assumptions!

VB.NET and C#VB.NET and C#Same platform, same performanceSame platform, same performance

But different language features can But different language features can perform differentlyperform differently

The key: Understand what you’re doingThe key: Understand what you’re doing

Page 7: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Timing Your CodeTiming Your Code

QueryPerformanceCounter provides QueryPerformanceCounter provides greatest level of granularitygreatest level of granularity

Requires Declare statementsRequires Declare statements

Package in class library for re-usePackage in class library for re-use

Page 8: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Maximizing PerformanceAll ApplicationsMaximizing PerformanceAll Applications

Page 9: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Use Option ExplicitUse Option ExplicitUse Option StrictUse Option Strict

Use Option ExplicitUse Option ExplicitUse Option StrictUse Option Strict

Page 10: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Don’t Late BindDon’t Late Bind

Calls on Object cause late bindingCalls on Object cause late bindingLate binding requires work at runtimeLate binding requires work at runtime

Binding is more complex than in Binding is more complex than in Visual Basic 6Visual Basic 6

Operators on Object cause late bindingOperators on Object cause late bindingNeeded because types can be anythingNeeded because types can be anything

Dim o, o1, o2 As ObjectDim o, o1, o2 As Object

o = o1 + o2o = o1 + o2 ' Late bound' Late bound

Option Strict will catch late bindingOption Strict will catch late binding

Page 11: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Call Stack

The call stackThe call stack

Code execution in .NET is based on the call stackCode execution in .NET is based on the call stackCall stack used to manage the flow of execution across Call stack used to manage the flow of execution across methodsmethods

Each method is allocated a stack frame for duration of Each method is allocated a stack frame for duration of executionexecution

Call stack used to store local variable and parameter valuesCall stack used to store local variable and parameter values

Stack frame torn down after method completesStack frame torn down after method completesModule MyApp

Sub Main() Dim x As Integer = 10 Method1(x) End Sub

Sub Method1(ByVal i As Integer) Dim y As Integer = i * 2 End Sub

End Module

x

10

i

10

y

20

stack frame for Main

stack frame for Method1

Page 12: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Value types vs. reference typesValue types vs. reference types

CTS supports two fundamentally different kinds of CTS supports two fundamentally different kinds of typestypes

value types (e.g. primitive types, structures, enumerations)value types (e.g. primitive types, structures, enumerations)

reference types (e.g. classes)reference types (e.g. classes)

CLR manages memory one way for value types CLR manages memory one way for value types instances of value types are simple valuesinstances of value types are simple values

variables based on value types contain actual valuesvariables based on value types contain actual values

typically instantiated without using New operatortypically instantiated without using New operator

CLR manages memory a different way for reference CLR manages memory a different way for reference typestypes

instances of reference types are first-class objectsinstances of reference types are first-class objects

variables based on reference types hold logical pointers to variables based on reference types hold logical pointers to objectsobjects

typically instantiated using New operatortypically instantiated using New operator

Page 13: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

CLR Memory managementCLR Memory management

Memory for value type allocated where variable is declaredMemory for value type allocated where variable is declaredvariable and value type instance are one and the samevariable and value type instance are one and the same

Memory for reference type instance always allocated on heapMemory for reference type instance always allocated on heapvariable and reference type instance are distinctvariable and reference type instance are distinct

variable either points to heap-based object or equals Nothingvariable either points to heap-based object or equals Nothing

Heap

Person Instanc

e

Module MyApp Sub Main() ' explicitly initialized value type instance Dim var1 As Integer = 34 ' auto-initialized value type instance Dim var2 As Integer ' explicitly initialized ref type variable Dim var3 As New Person() ' auto-initialized ref type variable Dim var4 As Person End SubEnd Module

Stack

var3

ref

var4

Nothing

var2

0

var1

34

Page 14: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Use The Right TypesUse The Right Types

Understand the two kinds of typesUnderstand the two kinds of typesReference types = ClassReference types = Class

Allocated on the heap, copies are freeAllocated on the heap, copies are free

Value types = Structure, Integer, etcValue types = Structure, Integer, etcAllocated on the stack, copies can have a costAllocated on the stack, copies can have a cost

““General” RecommendationGeneral” RecommendationValue types = small objects (Point, Size)Value types = small objects (Point, Size)

Reference types = bigger objects (Form)Reference types = bigger objects (Form)

There is no “one size fits all!”There is no “one size fits all!”

Page 15: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Avoid Slow ConversionsAvoid Slow Conversions

Value types to Object are “boxed”Value types to Object are “boxed”Involves a heap allocation and copyInvolves a heap allocation and copy

Conversions from Object call a helperConversions from Object call a helperDirectCast can avoid the helper call, but DirectCast can avoid the helper call, but only if the type is exactly right!only if the type is exactly right!

Dim x As Integer = DirectCast(o, Integer)Dim x As Integer = DirectCast(o, Integer)

Casts to/from String also call helpersCasts to/from String also call helpers

Option Strict will catch slow castsOption Strict will catch slow casts

Page 16: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Old vs. NewOld vs. New

CInt, CLng, CStr, etc. vs. CTypeCInt, CLng, CStr, etc. vs. CTypeNo differenceNo difference

Cxxx are not functions, they’re intrinsic Cxxx are not functions, they’re intrinsic parts of the languageparts of the language

Cxxx vs System.Convert.xxxCxxx vs System.Convert.xxxCan be a measurable differenceCan be a measurable difference

Be careful what you ask for … Cxxx Be careful what you ask for … Cxxx preserve “classic” VB semanticspreserve “classic” VB semantics

Page 17: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

DirectCastDirectCast

VB.NET language supplies DirectCast conversion operatorVB.NET language supplies DirectCast conversion operatorsyntax for converting with DirectCast same as with CTypesyntax for converting with DirectCast same as with CType

DirectCast can be faster than CTypeDirectCast can be faster than CTypeCType often results in implicit calls to Microsoft.VisualBasic.dllCType often results in implicit calls to Microsoft.VisualBasic.dll

DirectCast never results in calls to Microsoft.VisualBasic.dllDirectCast never results in calls to Microsoft.VisualBasic.dll

When is DirectCast faster?When is DirectCast faster?when converting from the Object type to the String typewhen converting from the Object type to the String type

when converting from the Object type to the numeric typeswhen converting from the Object type to the numeric types

Dim x As Object = CInt(2)Dim y As Integer = CType(x, Integer)Dim z As Object = DirectCast(x, Object)

Dim obj1 As Object = CInt(77)Dim obj2 As Object = "Hello world"‘ *** fastest VB.NET conversion techniquesDim o As object = DirectCast(obj1, Object)Dim s As String = DirectCast(obj2, String)

Page 18: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Array TipsArray Tips

Use arrays of arrays instead of Use arrays of arrays instead of multi-dimensional arraysmulti-dimensional arraysDim a()() As IntegerDim a()() As Integer ' Array of arrays' Array of arrays

Dim b(,) As IntegerDim b(,) As Integer ' Multi-dim array' Multi-dim array

Arrays of arrays are much faster for nowArrays of arrays are much faster for now

But arrays of arrays are not in the CLSBut arrays of arrays are not in the CLS

Use ArrayList object instead of Use ArrayList object instead of ReDim Preserve ReDim Preserve

ReDim Preserve copies the entire array!ReDim Preserve copies the entire array!

Page 19: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

String TipsString Tips

Strings are now immutableStrings are now immutableAllows many optimizationsAllows many optimizations

But now & operator allocates a new stringBut now & operator allocates a new string

StringBuilder builds long strings fasterStringBuilder builds long strings faster

Mid() assignment is not as efficientMid() assignment is not as efficientMid(s, 2, 4) = "abcd"Mid(s, 2, 4) = "abcd"

If globalization isn’t important…If globalization isn’t important…Use Option Binary instead of TextUse Option Binary instead of Text

Use .ToString instead of FormatUse .ToString instead of Format

Page 20: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Use String ConstantsUse String Constants

String constants are much faster nowString constants are much faster now

Concatenation of string constants is Concatenation of string constants is done at compile time when possibledone at compile time when possible

Don’t split across multiple statementsDon’t split across multiple statementss = "a" & "b" ' Optimizeds = "a" & "b" ' Optimized

s = "a" : s &= "b" ' Not optimizeds = "a" : s &= "b" ' Not optimized

Page 21: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Minimize ExceptionsMinimize Exceptions

Use exceptions only for errors!Use exceptions only for errors!Exceptions are NOT EventsExceptions are NOT Events

Throwing exceptions is expensiveThrowing exceptions is expensive

Use Try…Catch instead of On ErrorUse Try…Catch instead of On ErrorBetter code flow and designBetter code flow and design

Code generation is a little betterCode generation is a little betterEspecially if you used to use ResumeEspecially if you used to use Resume

Avoid going through the Error objectAvoid going through the Error object

Page 22: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Chunky, Not Chatty, CallsChunky, Not Chatty, Calls

Calls across runtime boundaries can Calls across runtime boundaries can be expensivebe expensive

Declare statementsDeclare statements

COM ObjectsCOM Objects

AppDomainsAppDomains

RemotingRemoting

Data marshalling may happenData marshalling may happen

Minimize calls, maximize data in a callMinimize calls, maximize data in a call

Page 23: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

General TipsGeneral Tips

Don’t…Don’t…allocate memory you don’t needallocate memory you don’t need

have large numbers of localshave large numbers of locals

write really large methods write really large methods

Use Overridable methods only when Use Overridable methods only when really neededreally needed

Calls to Overridable methods are a little Calls to Overridable methods are a little more expensivemore expensive

Use the Return statementUse the Return statementYou’ll get slightly better code generationYou’ll get slightly better code generation

Page 24: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Use Optimal Project OptionsUse Optimal Project Options

Use Release Builds!Use Release Builds!Debug = asserts, PDB, easily debuggableDebug = asserts, PDB, easily debuggable

Release = optimized, less debuggableRelease = optimized, less debuggable

You can set finer grain options in the You can set finer grain options in the project propertiesproject properties

Remove integer overflow checksRemove integer overflow checksCan speed up computationally intensive Can speed up computationally intensive applicationsapplications

But you lose overflow checking – But you lose overflow checking – be careful!be careful!

Page 25: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Maximizing PerformanceWindows Forms AppsMaximizing PerformanceWindows Forms Apps

Page 26: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

General Tips And TricksGeneral Tips And Tricks

Pay attention to application startupPay attention to application startupThe more code you load, the more time it takesThe more code you load, the more time it takes

Minimize the number of assemblies loadedMinimize the number of assemblies loaded

If there’s no need for data connection If there’s no need for data connection pooling, don’t use itpooling, don’t use it

you can save ~1 MB in working setyou can save ~1 MB in working setmySqlConnection = new SqlConnection("server=(local)\mySqlConnection = new SqlConnection("server=(local)\

NetSDK; …; database=northwind; NetSDK; …; database=northwind; Pooling = falsePooling = false")")

Use AddRange instead of AddUse AddRange instead of AddInstead of iteratively Add’ing each item use Instead of iteratively Add’ing each item use AddRange – for example, AddRange – for example, treeView1.Nodes.AddRange(treeNodes)treeView1.Nodes.AddRange(treeNodes)

Page 27: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Ngen To Start Up FasterNgen To Start Up Faster

A “pre-JITed” assembly (via ngen.exe) A “pre-JITed” assembly (via ngen.exe) is a persisted form of JITed MSILis a persisted form of JITed MSILReduces start-up time byReduces start-up time by

Compiling methods (JIT’ing) and doing Compiling methods (JIT’ing) and doing class/v-table layout ahead of timeclass/v-table layout ahead of timeEliminating mscorjit.dll from working setEliminating mscorjit.dll from working set

SDK contains several SDK contains several “pre-JITed” assemblies“pre-JITed” assemblies

mscorlib, windows forms, drawing, etc.mscorlib, windows forms, drawing, etc.

Native code has version checks and Native code has version checks and reverts to run-time JIT if they failreverts to run-time JIT if they fail

Page 28: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Ngen Trade-offsNgen Trade-offs

““ngen foo.exe” should be part of ngen foo.exe” should be part of app installapp install

Never “pre-jit” and copy assemblies Never “pre-jit” and copy assemblies

CLR does processor specific code-genCLR does processor specific code-gen

Breaks xcopy deploymentBreaks xcopy deployment

Doesn’t apply to ASP.NET apps at allDoesn’t apply to ASP.NET apps at all

Still need the original IL PE file to be Still need the original IL PE file to be deployed as CLR reads metadata theredeployed as CLR reads metadata there

Runtime perf (throughput) is slightly Runtime perf (throughput) is slightly worse due to indirections (~5%)worse due to indirections (~5%)

Page 29: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Maximizing PerformanceASP.NET ApplicationsMaximizing PerformanceASP.NET Applications

Page 30: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Design For CachingDesign For Caching

Leverage the built-in ASP .NET Leverage the built-in ASP .NET caching featurescaching features

Output CachingOutput CachingDeclarative Declarative <%@ OutputCache %><%@ OutputCache %> directive directive

Vary by duration, param, header, custom etc.Vary by duration, param, header, custom etc.

Fragment CachingFragment CachingCache regions of a page by using user controlsCache regions of a page by using user controls

Cache APICache APISystem.Web.Caching.Cache classSystem.Web.Caching.Cache class

RecommendationRecommendationSpecifically design your pages around these Specifically design your pages around these features, it can lead to massive performance winsfeatures, it can lead to massive performance wins

Page 31: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Use The Lowest Level Of Data Access In ADO.NETUse The Lowest Level Of Data Access In ADO.NET

Multiple ways to do data accessMultiple ways to do data accessSQL versus OLEDB ADO.NET ProviderSQL versus OLEDB ADO.NET Provider

DataReaders versus DataSets DataReaders versus DataSets

RecommendationsRecommendationsUse System.Data.SqlClient for SQL ServerUse System.Data.SqlClient for SQL Server

Use DataReaders for ASP.NET data Use DataReaders for ASP.NET data access when caching is not necessaryaccess when caching is not necessary

Avoid using unmanaged ADOAvoid using unmanaged ADO

Use stored proceduresUse stored procedures

Page 32: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Avoid Apartment TransitionAvoid Apartment Transition

Managed code is free threadedManaged code is free threadedOptimized for new .NET componentsOptimized for new .NET componentsVery sub-optimal for apartment-threaded Very sub-optimal for apartment-threaded components (for example, STA COM objects)components (for example, STA COM objects)

RecommendationsRecommendationsEnable the Enable the <%@ AspCompat=“true” %><%@ AspCompat=“true” %> directive directive for pages that use STA COM objectsfor pages that use STA COM objectsIf possible, upgrade (STA) COM components If possible, upgrade (STA) COM components to .NET (from Visual Basic 6.0 to Visual to .NET (from Visual Basic 6.0 to Visual Basic .NET)Basic .NET)Always generate early-bound managed wrappers Always generate early-bound managed wrappers for COM components (avoid late bound hit) for COM components (avoid late bound hit)

Reference the COM object in Visual Studio Reference the COM object in Visual Studio project (or tlbimp)project (or tlbimp)Minimize use of Server.CreateObjectMinimize use of Server.CreateObject

Page 33: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Maximizing PerformanceTools / ResourcesMaximizing PerformanceTools / Resources

Page 34: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

.NET Performance Counters.NET Performance Counters

Performance counters are metrics Performance counters are metrics about resource usage exposed by about resource usage exposed by the .NET Framework the .NET Framework

First line of defenseFirst line of defense

Always availableAlways available

Can be obtained non-intrusively even Can be obtained non-intrusively even in production environmentin production environment

Page 35: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

ResourcesResources

Code ToolsCode ToolsLutz Roeder’s ReflectorLutz Roeder’s Reflector

http://www.aisto.com/roeder/dotnet/http://www.aisto.com/roeder/dotnet/

NuMega: DevPartner ProfilerNuMega: DevPartner Profilerhttp://www.compuware.com/products/numega/http://www.compuware.com/products/numega/dps/profiler/dps/profiler/

Books & ArticlesBooks & ArticlesToo Many to ListToo Many to List

See Text Document in DownloadSee Text Document in Download

Page 36: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

SamplesSamples

Later today, code I wrote will be on Later today, code I wrote will be on CommNetCommNet

——Or—Or—

http://www.mcwtech.com/2004/teched/us/http://www.mcwtech.com/2004/teched/us/

Page 37: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Final TipsFinal Tips

Program for correctness firstProgram for correctness first

But …But …Measure performance as early as possibleMeasure performance as early as possible

Avoid monolithic classes and assembliesAvoid monolithic classes and assemblies—factor!—factor!

Consider implementing performance Consider implementing performance counters and instrumentation tools for counters and instrumentation tools for your applicationsyour applications

Page 38: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

Thank You!Thank You!

Enjoy the rest of the show!Enjoy the rest of the show!

Please fill out your evaluationsPlease fill out your evaluations

Questions?Questions?See me after the talkSee me after the talk

See me later this weekSee me later this week

E-mail:E-mail:To: brianr AT mcwtech DOT comTo: brianr AT mcwtech DOT com

Subject: TECH ED 2004 DEV340Subject: TECH ED 2004 DEV340

Page 39: DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications Brian A. Randell Senior Consultant MCW Technologies, LLC

© 2004 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.