where developers meet development
Saturday,September 11,2010
CollabNet Intends to Become No.1 in Agile ALM by Acquiring Danube   Enterprise consolidation is the order of the day and here is another piece...
Micro Focus Integrates Visual Studio 2010 in Cobol Tools   Micro Focus has announced four new Cobol products to allow developers to...
ODA Open Design Alliance Announces DWGdirect.NET Beta Release   The Open Design Alliance (ODA) announces the beta release of DWGdirect.NET,...
Hot and Safe: a Beginner's Guide to Multithreaded Libraries   Most of the discussion of multithreading that emerges from Cilk Arts is...
8 Simple Rules for Designing Threaded Applications   Multithreaded programming is still more art than science. This white paper...
 

EXCLUSIVES 

Writing High Performance .NET Code

Tips for Improving Manage Code Performance

We covered threading and GC and now we cover the general VM, code generation and basic ASP.NET and ADO.NET tips for writing better code

a. Avoid unnecessary boxing [1]


 int i = 123;
 object o = i; (Implicit boxing) //box keyword
 int j = (int)o; //unbox keyword

When ever we box, a new object is created on the managed heap and the value is copied in it. If we are doing this frequently, then we will create lot of objects (affect GC) and also the extra code we execute for boxing and unboxing.

b. Consider using strong typed arrays or generics (Visual Studio 2005 onwards)


 Foo myFoo = new Foo();
 myArrayList.Add(myFoo);
 Foo myFoo = (Foo) myArrayList[i]; //castclass keyword


Collection classes take generic “object” as a parameter. Type casting is required when retrieving objects(your type) from the collection classes. This requires an expensive run time type check by looking at method table of that object. If your object is inherited then this may require traversing one level up which is again expensive. You can avoid this by using generics (similar to C++ template) as shown below which doesn’t require run time type check as it is known at the compile time.


 List myList = new List();
 Foo myfoo = myList[i]; //no check reqd


c. Throw fewer exceptions: Throwing exceptions can be expensive as stalk walk is required etc for managing the frames. Don’t use exceptions as a control flow in your application



void foo (int parameter)
{ int ret = 0;
  val = …. ;
  try
    {
      ret = val / parameter;
    }catch(DivideByZeroException) { return ERROR_VAL ;}
}


void foo (int parameter)
{
    if (parameter == 0) return ERROR_VAL; else {… ;}
}


d. Use StringBuilder for complex string manipulation: Whenever you modify a string (such as append etc), it will create a new string leaving the first one to be collected. Consider using a StringBuilder if you have > 5-7 string manipulations.
e. Don’t use too many Reflection API’s: Reflection API’s depend on the metadata embedded in assemblies. Thus parsing and searching this information is very expensive.
f. Don’t make functions unnecessarily virtual or synchronized: JIT might disable some optimizations and so the generated code might not be optimal
g. Don’t write big functions: JIT might disable optimizations for faster compile (JIT) time.
h. Avoid calling small functions inside loop: Consider inlining yourself (incase JIT has not done it). Any mistake in the loop is magnified.
i. Prefer arrays to collections unless you need that additional functionality that collection classes provide [1]
j. Use jagged arrays instead of multi dimensional arrays since the former has some special MSIL optimizations for faster array access [1]
k. Smaller working set produces better performance and so consider using ngen for shared pages
l. Don’t make too many Pinvoke calls (chatty calls) and do less work in unmanaged code: The overhead of transitions (managed to unmanaged and back) can negate performance speedup or even hurt.

Ngen: Ngen.exe (shipped with CLR) invokes JIT compiler on MSIL to create native code and stores it in the disk. Once the native image is created, runtime uses this image automatically each times it runs the assembly. Using native image will eliminate compiling on the fly using JIT compiler at runtime thus reducing application startup time.

Ngen.exe can help improving application performance by:

  • Reducing the application startup time – Consider using ngen.exe for improving startup time of your winform based application. Always measure with and without ngening of your application.
  • By reducing the total memory consumed by application that use shared assemblies (which are loaded in to different application domains)
Interop: When you build applications in managed code, some times it is necessary to call unmanaged libraries such as calling a COM component. In some cases, you want to use unmanaged code for some performance related reasons as well (such as calling 3rd party highly optimized libraries). CLR provides several ways to do this.

  • Using Pinvoke (Platform Invoke) – Allows calling of Windows DLL’s, Win32 API’s or custom dll’s from managed code (1)
  • Using MC++ (IJW) – For users for MC++ to call standard DLL’s (1)
  • COM Interop – Manage languages to call COM components through COM interfaces. (1)
Improving Interop Performance

  • Avoid chatty calls that increase unnecessary round trips: Increases the overhead due to multiple transitions
  • Avoid inefficient marshalling of parameters: this causes unnecessary waste of system processing cycles
  • Properly cleanup (dispose) unmanaged components: This can affect server’s memory utilization and can cause memory leaks
  • Don’t aggressively pin the short lived objects: This can create fragmentation in managed heap hurting performance.

Improving ASP.NET Performance

a. Use efficient caching strategies (1): A well designed caching strategies is the single most important consideration during design phase of your application. There are different caching methods such as output caching, partial page caching etc can reduce round trips to database. It is very important to do analysis to figure out where caching is appropriate. You want to consider caching if:

  a.a. The data or output is very expensive to create or fetch
  a.b. Frequency of use
  a.c. The data is fairly static and is not changing frequently


b. Partition your application logically: Presentation, business logic, ado.net (database) layer so it is easy to maintain and optimize individual layers (1)

c. Consider disabling IIS logging on application server

d. Use server controls efficiently: This can increase the page load time.

e. Improve page response times: Use Page.IsPostBack to minimize the round trip to server

f. Ensure pages are batch compiled: If we mix different languages in the same directory then it won’t compile all the pages into 1 assembly.

g. Ensure the debug attribute is not set on pages

h. Validate and fail early to avoid expensive work

i. Use view state only when necessary – View state is serialized and deserialized on the server which is expensive

The Entire Game Should Move Onto the GPU, says Rev Lebaredian   As the computing functionality and horsepower of GPUs has grown over the last few years, the role of the GPU is rapidly expanding to game tasks beyond rasterization-based graphics. Now...
The Entire Game Should Move Onto the GPU, says Rev Lebaredian   As the computing functionality and horsepower of GPUs has grown over the last few years, the role of the GPU is rapidly expanding to game tasks beyond rasterization-based graphics. Now...
SOA with SQL Server   A key component to any distributed architecture built with SOA methodologies in mind is the database infrastructure. Service Oriented Database Architecture (SODA) is much easier to...
A Lap Around Visual Studio Team System   Wonder why 70% of projects are classified as failed projects? Working in silos does not help projects succeed. Learn how Visual Studio Team System 2008 helps break the walls across team...
Busting Common Myths about Developer Productivity   Many traditional assumptions about software development have been challenged in recent years. Agile processes and service oriented architectures are two examples of this. An area that has...
.NET Gotchas Workshop by Venkat Subramaniam: Part III   Programmers working on the .NET framework know the power and increased productivity that comes with it, says Dr. Venkat Submramaniam. Like any development, however, there are things that...
Silverlight Deep Dive Workshop by Todd Anglin: Part III   Do you want to truly understand Silverlight? If so, do not miss this three-hour workshop that will cover everything from Silverlight basics to advanced topics like cross-site XHR. In the...
.NET Gotchas Workshop: Part II   There are several things that one should pay attention to while programming on .NET, says Dr. Venkat Submramaniam. Are there things in .NET that, if we do not pay attention to, may result...
To:
Name:*
E-mail address:*
Your Details:
Your name: *
E-mail address: *
Message:
Software Supportby Advanced Millennium Technologies

Advanced Millennium Technologies. Expertise in software development, offering consultancy services, Open source programming, CRM - Customer Relationship Management, CMS - Content Management System , ERP - Enterprise Resource Planning and Ecommerce development, AJAX, PHP, .NET, J2EE, SOA, XSLT, DOJO toolkit development and software testing. A robust onsite-offshore model. A well-defined global delivery model. AMT Outsourcing center. www.amt.inTAROBY - The E-Mail Dashboard for EntrepreneursTaroby is a SaaS based messaging and collaboration suite inbox that enables sharing of email accounts among team members. The unique concept of 'Team Inbox' makes Taroby an excellent enterprise collaboration suite for enterprises. Taroby is an effective tool for CEO's and entrepreneurs to manage multiple departments or manage multiple projects under them. The team inbox gives the entrepreneurs an overview of what is happening their business and give a quick snap shot of the employees who is responcible for handling the tasks/emails. For team members taroby brings in transparency and efficiency in their teams. Taroby improves the internal and external communication in an organization. Using the Taroby's Team Inbox also helps in reducing the usage of disc space and there by helping the enterprises to reduce carbon footprints.