1 / 39

DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications

DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications. Brian A. Randell Senior Consultant MCW Technologies, LLC. Me.About. Senior Consultant with MCW Technologies A Microsoft Certified Partner www.mcwtech.com Co-author Effective Visual Basic ISBN: 0201704765 Blog

yepa
Télécharger la présentation

DEV340 Visual Basic Tips and Tricks for Optimizing Your Applications

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Me.About • Senior Consultant with MCW Technologies • A Microsoft Certified Partner • www.mcwtech.com • Co-author Effective Visual Basic • ISBN: 0201704765 • Blog • http://sqljunkies.com/WebLog/brianr/

  3. Thanks to • Paul VickDevelopment Lead, CompilerVisual BasicMicrosoft Corporation • Mahesh PrakriyaLead Program ManagerCommon Language RuntimeMicrosoft CorporationThey wrote most of this talk.

  4. Outline • Introduction • Tips and tricks for • All applications • Windows Forms applications • ASP.NET applications • Tools/Resources

  5. Remember There are three kinds of lies: lies, damn lies, and statistics. Benjamin DisraeliPrime Minister of the British Empire1874-1880

  6. Introduction • VB.NET and Visual Basic 6.0 • Different platforms, different performance • .NET is a great platform for performance • Just don’t make assumptions! • VB.NET and C# • Same platform, same performance • But different language features can perform differently • The key: Understand what you’re doing

  7. Timing Your Code • QueryPerformanceCounter provides greatest level of granularity • Requires Declare statements • Package in class library for re-use

  8. Maximizing PerformanceAll Applications

  9. Use Option ExplicitUse Option Strict

  10. Don’t Late Bind • Calls on Object cause late binding • Late binding requires work at runtime • Binding is more complex than in Visual Basic 6 • Operators on Object cause late binding • Needed because types can be anything • Dim o, o1, o2 As Object • o = o1 + o2 ' Late bound • Option Strict will catch late binding

  11. The call stack • Code execution in .NET is based on the call stack • Call stack used to manage the flow of execution across methods • Each method is allocated a stack frame for duration of execution • Call stack used to store local variable and parameter values • Stack frame torn down after method completes Call Stack Module 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 stack frame for Main 10 i 10 stack frame for Method1 y 20

  12. Value types vs. reference types • CTS supports two fundamentally different kinds of types • value types (e.g. primitive types, structures, enumerations) • reference types (e.g. classes) • CLR manages memory one way for value types • instances of value types are simple values • variables based on value types contain actual values • typically instantiated without using New operator • CLR manages memory a different way for reference types • instances of reference types are first-class objects • variables based on reference types hold logical pointers to objects • typically instantiated using New operator

  13. ref CLR Memory management • Memory for value type allocated where variable is declared • variable and value type instance are one and the same • Memory for reference type instance always allocated on heap • variable and reference type instance are distinct • variable either points to heap-based object or equals Nothing 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 Sub End Module Stack var1 Heap 34 var2 Person Instance 0 var3 var4 Nothing

  14. Use The Right Types • Understand the two kinds of types • Reference types = Class • Allocated on the heap, copies are free • Value types = Structure, Integer, etc • Allocated on the stack, copies can have a cost • “General” Recommendation • Value types = small objects (Point, Size) • Reference types = bigger objects (Form) • There is no “one size fits all!”

  15. Avoid Slow Conversions • Value types to Object are “boxed” • Involves a heap allocation and copy • Conversions from Object call a helper • DirectCast can avoid the helper call, but only if the type is exactly right! Dim x As Integer = DirectCast(o, Integer) • Casts to/from String also call helpers • Option Strict will catch slow casts

  16. Old vs. New • CInt, CLng, CStr, etc. vs. CType • No difference • Cxxx are not functions, they’re intrinsic parts of the language • Cxxx vs System.Convert.xxx • Can be a measurable difference • Be careful what you ask for … Cxxx preserve “classic” VB semantics

  17. DirectCast • VB.NET language supplies DirectCast conversion operator • syntax for converting with DirectCast same as with CType • DirectCast can be faster than CType • CType often results in implicit calls to Microsoft.VisualBasic.dll • DirectCast never results in calls to Microsoft.VisualBasic.dll • When is DirectCast faster? • when converting from the Object type to the String type • when 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 techniques Dim o As object = DirectCast(obj1, Object) Dim s As String = DirectCast(obj2, String)

  18. Array Tips • Use arrays of arrays instead of multi-dimensional arrays Dim a()() As Integer ' Array of arrays Dim b(,) As Integer ' Multi-dim array • Arrays of arrays are much faster for now • But arrays of arrays are not in the CLS • Use ArrayList object instead of ReDim Preserve • ReDim Preserve copies the entire array!

  19. String Tips • Strings are now immutable • Allows many optimizations • But now & operator allocates a new string • StringBuilder builds long strings faster • Mid() assignment is not as efficient • Mid(s, 2, 4) = "abcd" • If globalization isn’t important… • Use Option Binary instead of Text • Use .ToString instead of Format

  20. Use String Constants • String constants are much faster now • Concatenation of string constants is done at compile time when possible • Don’t split across multiple statements s = "a" & "b" ' Optimized s = "a" : s &= "b" ' Not optimized

  21. Minimize Exceptions • Use exceptions only for errors! • Exceptions are NOT Events • Throwing exceptions is expensive • Use Try…Catch instead of On Error • Better code flow and design • Code generation is a little better • Especially if you used to use Resume • Avoid going through the Error object

  22. Chunky, Not Chatty, Calls • Calls across runtime boundaries can be expensive • Declare statements • COM Objects • AppDomains • Remoting • Data marshalling may happen • Minimize calls, maximize data in a call

  23. General Tips • Don’t… • allocate memory you don’t need • have large numbers of locals • write really large methods • Use Overridable methods only when really needed • Calls to Overridable methods are a little more expensive • Use the Return statement • You’ll get slightly better code generation

  24. Use Optimal Project Options • Use Release Builds! • Debug = asserts, PDB, easily debuggable • Release = optimized, less debuggable • You can set finer grain options in the project properties • Remove integer overflow checks • Can speed up computationally intensive applications • But you lose overflow checking – be careful!

  25. Maximizing PerformanceWindows Forms Apps

  26. General Tips And Tricks • Pay attention to application startup • The more code you load, the more time it takes • Minimize the number of assemblies loaded • If there’s no need for data connection pooling, don’t use it • you can save ~1 MB in working set mySqlConnection = new SqlConnection("server=(local)\NetSDK; …; database=northwind; Pooling = false") • Use AddRange instead of Add • Instead of iteratively Add’ing each item use AddRange – for example, treeView1.Nodes.AddRange(treeNodes)

  27. Ngen To Start Up Faster • A “pre-JITed” assembly (via ngen.exe) is a persisted form of JITed MSIL • Reduces start-up time by • Compiling methods (JIT’ing) and doing class/v-table layout ahead of time • Eliminating mscorjit.dll from working set • SDK contains several “pre-JITed” assemblies • mscorlib, windows forms, drawing, etc. • Native code has version checks and reverts to run-time JIT if they fail

  28. Ngen Trade-offs • “ngen foo.exe” should be part of app install • Never “pre-jit” and copy assemblies • CLR does processor specific code-gen • Breaks xcopy deployment • Doesn’t apply to ASP.NET apps at all • Still need the original IL PE file to be deployed as CLR reads metadata there • Runtime perf (throughput) is slightly worse due to indirections (~5%)

  29. Maximizing PerformanceASP.NET Applications

  30. Design For Caching • Leverage the built-in ASP .NET caching features • Output Caching • Declarative <%@ OutputCache %> directive • Vary by duration, param, header, custom etc. • Fragment Caching • Cache regions of a page by using user controls • Cache API • System.Web.Caching.Cache class • Recommendation • Specifically design your pages around these features, it can lead to massive performance wins

  31. Use The Lowest Level Of Data Access In ADO.NET • Multiple ways to do data access • SQL versus OLEDB ADO.NET Provider • DataReaders versus DataSets • Recommendations • Use System.Data.SqlClient for SQL Server • Use DataReaders for ASP.NET data access when caching is not necessary • Avoid using unmanaged ADO • Use stored procedures

  32. Avoid Apartment Transition • Managed code is free threaded • Optimized for new .NET components • Very sub-optimal for apartment-threaded components (for example, STA COM objects) • Recommendations • Enable the <%@ AspCompat=“true” %> directive for pages that use STA COM objects • If possible, upgrade (STA) COM components to .NET (from Visual Basic 6.0 to Visual Basic .NET) • Always generate early-bound managed wrappers for COM components (avoid late bound hit) • Reference the COM object in Visual Studio project (or tlbimp) • Minimize use of Server.CreateObject

  33. Maximizing PerformanceTools / Resources

  34. .NET Performance Counters • Performance counters are metrics about resource usage exposed by the .NET Framework • First line of defense • Always available • Can be obtained non-intrusively even in production environment

  35. Resources • Code Tools • Lutz Roeder’s Reflector • http://www.aisto.com/roeder/dotnet/ • NuMega: DevPartner Profiler • http://www.compuware.com/products/numega/dps/profiler/ • Books & Articles • Too Many to List • See Text Document in Download

  36. Samples • Later today, code I wrote will be on CommNet —Or— • http://www.mcwtech.com/2004/teched/us/

  37. Final Tips • Program for correctness first • But … • Measure performance as early as possible • Avoid monolithic classes and assemblies—factor! • Consider implementing performance counters and instrumentation tools for your applications

  38. Thank You! • Enjoy the rest of the show! • Please fill out your evaluations • Questions? • See me after the talk • See me later this week • E-mail: • To: brianr AT mcwtech DOT com • Subject: TECH ED 2004 DEV340

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

More Related