Upload
mae-freeman
View
218
Download
0
Embed Size (px)
Citation preview
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
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/
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.
OutlineOutline
IntroductionIntroduction
Tips and tricks forTips and tricks forAll applicationsAll applications
Windows Forms applicationsWindows Forms applications
ASP.NET applicationsASP.NET applications
Tools/ResourcesTools/Resources
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
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
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
Maximizing PerformanceAll ApplicationsMaximizing PerformanceAll Applications
Use Option ExplicitUse Option ExplicitUse Option StrictUse Option Strict
Use Option ExplicitUse Option ExplicitUse Option StrictUse Option Strict
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
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
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
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
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!”
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
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
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)
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!
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
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
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
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
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
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!
Maximizing PerformanceWindows Forms AppsMaximizing PerformanceWindows Forms Apps
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)
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
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%)
Maximizing PerformanceASP.NET ApplicationsMaximizing PerformanceASP.NET Applications
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
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
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
Maximizing PerformanceTools / ResourcesMaximizing PerformanceTools / Resources
.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
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
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/
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
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
© 2004 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.