Thursday, April 10, 2008

Tips to improve performance of Web applications - 1

In Web.config
  • Turn off Tracing unless until required.

    Turn off session state in web.config file or at least for a page if there is no sessions.

  • set debug=false

  • Increase the Pool "Packet size" for transferring large blob or image fields
    In connection string set "Packet Size= Required number". Performance decreases if the Packet size is huge for small amount of data transfers.

In Web Applications

1. Per-Request Caching

2. Cache API (Data set)

3. Background Processing (sending mails through timer 5-min)

4. Page Output Caching

5. Run IIS 6.0

6. Use Gzip Compression

7. Disable View State of a Page or Datagrid if possible.

An example of View State might be a long form that users must fill out: if they click Back in their browser and then return, the form will remain filled. When this functionality isn't used, this state eats up memory and performance. Perhaps the largest performance drain here is that a round-trip signal must be sent across the network each time the page is loaded to update and verify the cache. Since it is on by default, you will need to specify that you do not want to use View State with


<@% EnabledViewState = false %>.

8. Use Response.Redirect (".aspx",false) instead of response.redirect(".aspx"). It reduces CLR Exceptions count.


9 String Builder in place of string when ever needed


When a string is modified, the run time will create a new string and return it, leaving the original to be garbage collected. Most of the time this is a fast and simple way to do it, but when a string is being modified repeatedly it begins to be a burden on performance: all of those allocations eventually get expensive. To solve this Use String Builder when ever needed.

10. Fragment caching
Cache the "User controls" whenever those are repeated in several forms in a project.
11. Avoid Throwing Exceptions. It is very expensive.

Finding and designing away exception-heavy code can result in a decent perf win. Bear in mind that this has nothing to do with try/catch blocks: you only incur the cost when the actual exception is thrown. You can use as many try/catch blocks as you want. Using exceptions gratuitously is where you lose performance. For example, you should stay away from things like using exceptions for control flow.

12. Change into Release mode
Select the Release mode before making the final Build for your application. By default it is in Debug mode.

13. Use Finally Method to kill resources.

Ideal Finally block:

If Not SqlDr Is Nothing Then SqlDr.Close() End If

If Not sqlcon Is Nothing Then Sqlcon.Close() End If

14. Validate all Input received from the Users.

Use Client Side Validations as much as possible. However, do a check at the Server side too to avoid the infamous Javascript disabled scenarios.

15. Avoid Recursive Functions / Nested Loops

16. Enable Option Strict and Option Explicit for your pages.

With Option Strict on, you protect yourself from inadvertent late binding and enforce a higher level of coding discipline.

Option Explicit is less restrictive than Option Strict, but it still forces programmers to provide more information in their code. Specifically, you must declare a variable before using it.

17. Use early binding in Visual Basic or JScript code.

Visual Basic 6 does a lot of work under the hood to support casting of objects, and many programmers aren't even aware of it. In Visual Basic 7, this is an area that out of which you can squeeze a lot of performance. When you compile, use early binding. This tells the compiler to insert a Type Coercion is only done when explicitly mentioned. This has two major effects:

a. Strange errors become easier to track down.

b. Unneeded coercions are eliminated, leading to substantial performance improvements.

When you use an object as if it were of a different type, Visual Basic will coerce the object for you if you don't specify. This is handy, since the programmer has to worry about less code.

18. Use Response.Write for String concatenation


Use the HttpResponse.Write method in your pages or user controls for string concatenation.


This method offers buffering and concatenation services that are very efficient. If you are performing extensive concatenation, however, the technique in the following example, using multiple calls to Response.Write, is faster than concatenating a string with a single call to the Response.Write method.

19. Avoid unnecessary round trips to the server

a. Implement Ajax UI whenever possible. The idea is to avoid full page refresh and only update the portion of the page that needs to be changed. I think Scott's article gave great information on how to implement Ajax Atlas and control.

b. Use Client Side Scripts. Client site validation can help reduce round trips that are required to process user's request. In ASP.NET you can also use client side controls to validate user input.

c. Use Page.ISPostBack property to ensure that you only perform page initialization logic when a page first time loaded and not in response to client postbacks.

If Not IsPostBack Then

LoadJScripts()

EndIf

d. In some situations performing postback event handling are unnecessary. You can use client callbacks to read data from the server instead of performing a full round trip.

20. Minimize the Use of Format()

When you can, use toString() instead of format(). In most cases, it will provide you with the functionality you need, with much less overhead.

21. Optimize Assignments

Use exp += val instead of exp = exp + val. Since exp can be arbitrarily complex, this can result in lots of unnecessary work. This forces the JIT to evaluate both copies of exp, and many times this is not needed. The first statement can be optimized far better than the second, since the JIT can avoid evaluating the exp twice.

22. Include Return Statements with in the Function

Explicitly using return allows the JIT to perform slightly more optimizations. Without a return statement, each function is given several local variables on stack to transparently support returning values without the keyword. Keeping these around makes it harder for the JIT to optimize, and can impact the performance of your code. Look through your functions and insert return as needed. It doesn't change the semantics of the code at all, and it can help you get more speed from your application

23. Use For Loops for String Iteration

The tradeoff for this generalization is speed, and if you rely heavily on string iteration you should use a For loop instead. Since strings are simple character arrays, they can be walked using much less overhead than other structures.

Foreach is far more readable, and in the future it will become as fast as a For loop for special cases like strings. Unless string manipulation is a real performance hog for you, the slightly messier code may not be worth it.

24.Precompiling pages and disabling AutoEventWireup

By precompiled pages, users do not have to experience the batch compile of your ASP.NET files; it will increase the performance that your users will experience.

Also setting the AutoEventWireup attribute to false in the Machine.config file means that the page will not match method names to events and hook them up (for example, Page_Load). If page developers want to use these events, they will need to override the methods in the base class (for example, they will need to override Page.OnLoad for the page load event instead of using a Page_Load method). If you disable AutoEventWireup, your pages will get a slight performance boost by leaving the event wiring to the page author instead of performing it automatically.

25. Use Jagged Arrays instead of rectangular Arrays

The v1 JIT optimizes jagged arrays (simply 'arrays-of-arrays') more efficiently than rectangular arrays, and the difference is quite noticeable. Here is a table demonstrating the performance gain resulting from using jagged arrays in place of rectangular ones in both C# and Visual Basic

26. Put Concatenations in One Expression

If you have multiple concatenations on multiple lines, try to stick them all on one expression. The compiler can optimize by modifying the string in place, providing a speed and memory boost. If the statements are split into multiple lines, the Visual Basic compiler will not generate the Microsoft Intermediate Language (MSIL) to allow in-place concatenation.

27. Avoid Unnecessary Indirection

When you use byRef, you pass pointers instead of the actual object. Many times this makes sense (side-effecting functions, for example), but you don't always need it. Passing pointers results in more indirection, which is slower than accessing a value that is on the stack. When you don't need to go through the heap, it is best to avoid it.

28. Use Charw

Use charw instead of char. The CLR uses Unicode internally, and char must be translated at run time if it is used. This can result in a substantial performance loss, and specifying that your characters are a full word long (using charw) eliminates this conversion.

29. Use Binary Compare for Text

When comparing text, use binary compare instead of text compare. At run time, the overhead is much lighter for binary.

30. Partial Classes (or Split classes)

Partial classes can improve code readability and maintainability by providing a powerful way to extend the behavior of a class and attach functionality to it.

One of the language enhancements in .NET 2.0-available to both VB2005 and C# 2.0 programmers-is support for partial classes. In a nutshell, partial classes mean that your class definition can be split into multiple physical files. Logically, partial classes do not make any difference to the compiler. During compile time, it simply groups all the various partial classes and treats them as a single entity.

One of the greatest benefits of partial classes is that they allow a clean separation of business logic and the user interface (in particular, the code that is generated by the Visual Studio Designer). Using partial classes, the UI code can be hidden from the developer, who usually has no need to access it anyway. Partial classes also make debugging easier, as the code is partitioned into separate files. This feature also helps members of large development teams work on their pieces of a project in separate physical files.

31. Use "array Lists" in place of arrays.

An ArrayList as everything that is good about an array PLUS automatic sizing, Add, Insert, Remove, Sort, BinarySearch. All these great helper methods are added when implementing the IList interface, the specifics of which are explored in the next section. The downside of an ArrayList is the need to cast objects upon retrieval.

32. Use "For each" Instead of For.

While writing this sample, we forgot to subtract one from people.Length. It was an immediately obvious mistake, but it could have been avoided by using

For Each.


When you use "For each" with an array, as you did here, the compiled Intermediate Language (IL) code is identical to the code you wrote as a For. Unless you require more complex behavior, such as iterating in reverse or iterating over every other item, always be sure to use For Each to iterate over arrays and most collections. The language-specific compiler handles this expansion and you reap the benefit. Your code will be less prone to off-by-one bugs, and it will be much easier to read.

33. Appropriate data type based on the requirement.

Use binary, int16, int32, int64 in place of integer according to the need..




No comments: