Introduction
.NET Application performance Tips and Tricks
Changes have to be Done in Web.Config and Mechine.config File
-------------------------------------------------------------
1.Set debug=false under compilation as follows:-
<compilation defaultLanguage="c#" debug="false">
When you create the application, by default this attribute is set to "true" which is very useful while developing. However,when you are deploying your application, always set it to "false"
Setting it to "true" requires the pdb information to be inserted into the file and this results in a comparatively larger file and hence processing will be slow.
2. Turn off Tracing unless until required.
Tracing is one of the wonderful features which enable us to track the application's trace and the sequences. However, again it is useful only for developers and you can set this to "false" unless you require to monitor the trace logging.
Before you deploy your application, disable tracing and debugging. Tracing and debugging may cause performance issues. Tracing and debugging are not recommended while your application is running in production. You can disable tracing and debugging in the Machine.config and Web.config using the syntax below.
You can turn off tracing as follows:-
<configuration>
<system.web>
<trace enabled="false" pageOutput="false" />
<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"/>
<compilation debug="false" />
</system.web>
</configuration>
3. Turn off Session State, if not required.
ASP.NET Manages session state automatically. However, in case you dont require Sessions, disabling it will help in improving the performance.
You may not require seesion state when ur pages r static or whn u dont need to store infor captured in the page.
You can turn off session state as follows:-
<sessionstate timeout="20" cookieless="false" mode="Off" stateconnectionstring="tcpip=127.0.0.1:42424"
sqlconnectionstring="data source=127.0.0.1;Trusted_Connection=no">
For doing it in Page wise
<%@ Page EnableSessionState="false" %>
Changes have to be Done when building .NET Application
----------------------------------------
4. Select the Release mode before making the final Build for your application. This option is available in the Top Frame just under the Window Menu option. By default, the Mode is Debug
There are several things happening when you Build/Re-Build applications in the Debug Mode. First of all, it creates an additional PDB File under your BIN directory. This holds all the Debug information.
Secondly, the Timeout is very high since you require higher time out frequency while debugging such that your process hangs on until you get to the exact break point where error is there.
So, selecting Release Mode will greatly improve the performance of the application when u deploy.
General Methods to improve the Performance of Web Application
-------------------------------------------------------------
5. Disable ViewState when not required.
6. Avoid Frequent round trips to the Database.
Calls made to Database can be quite expensive in terms of response time as well as resources and it can be avoided by using Batch Processing.
Make calls to Database as mininal as possible and make them last even lesser time. Use of DataAdapter wherever applicable is very useful since, it automatically opens and closes Connection whenever required and doesnt require user to explicitly open the connection.
A number of connections opened and not closed adequately can directly influence in performance slow down.
7. Avoid Throwing Exceptions. It is very expensive.
8. Use Caching to improve the performance of your application.
9. Use appropriate Authentication Mechanism.
The Authentication Mechanism you choose determines the cost associated with it and hence select the appropriate mechanism. An informal but useful order is as follows:-
Authentication Modes
1. None
2. Windows
3. Forms
4. Passport
10. 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.
11. Use Finally Method to kill resources.
In your Try..Catch.. Block, always use the Finally method to close Open connections, Open DataReaders, Files and other resources such that they get executed independent of whether the code worked in Try or went to Catch.
12. The String and Stringbuilder Usage.
If you are initially creating a string say s = "Hello". Then you are appending to it as s = s + " World"; You are actually creating two instances of string in memory. Both the original as well as the new string will be stored in the memory. For that matter, all the activities you do to the string are stored in the memory as separate references and it must be avoided as much as possible.
Use StringBuilder which is very useful in these kind of scenarios. For the example above, using a StringBuilder as
s.Append(" World"); which only stores the value in the original string and no additional reference is created.
Eg:
String Action
--------------
string str="";
DateTime startTime = DateTime.Now;
Response.Write(("<br>Start time:" + startTime.ToString()));
int i;
for(i=0;i<20000;i++)
{
str += i.ToString()+ "<br>";
}
DateTime EndTime= DateTime.Now;
Response.Write(("<br>End time:" + EndTime.ToString()));
Out Put:
Start time:3/22/2006 10:23:44 AM
End time:3/22/2006 10:25:08 AM
The above code took 1 minutes and 24 Seconds to complete its operation
String Builder Action
---------------------
StringBuilder strbuilder = new StringBuilder();
DateTime startTime1 = DateTime.Now;
Response.Write(("<br>Start time:" + startTime1.ToString()));
int i1;
for (i1 = 0; i1 < 20000; i1++)
{
strbuilder.Append(i1 + "<br>");
}
DateTime EndTime1 = DateTime.Now;
Response.Write(("<br>End time:" + EndTime1.ToString()));
Out Put:
Start time:3/22/2006 10:25:08 AM
End time:3/22/2006 10:25:09 AM
The above code took 1 Seconds to complete its operation
13. Avoid Recursive Functions / Nested Loops
14. Enable Option Strict and Option Explicit for your pages.
15. Use early binding in Visual Basic or JScript code.
16. 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.
Response.Write("a");
Response.Write(myString);
Response.Write("b");
Response.Write(myObj.ToString());
Response.Write("c");
Response.Write(myString2);
Response.Write("d");
17. Avoid unnecessary round trips to the server:
Use Page.IsPostback to avoid extra work on a round trip.
• 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 <atlas:updatepanel> control.
• 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.
• 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()
End If
• 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.
18. Keep IO Buffer Size Between 4KB and 8KB
For nearly every application, a buffer between 4KB and 8KB will give you the maximum performance. For very specific instances, you may be able to get an improvement from a larger buffer (loading large images of a predictable size, for example), but in 99.99% of cases it will only waste memory. All buffers derived from BufferedStream allow you to set the size to anything you want, but in most cases 4 and 8 will give you the best performance
19. 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.
20. 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.
21. Include Return Statements with in the Function
22. Use For Loops for String Iteration
23. Explicitly Dispose or Close all the resources:
Try
_con.Open()
Catch ex As Exception
Throw ex
Finally
If Not _con Is Nothing Then
_con.Close()
End If
End Try
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.
Database
--------
1.Use the Optimal Managed Provider
2.Use Stored Procedures Whenever Possible
3.Use SqlDataReader Instead of Dataset wherevr it is possible
3.Turn Off Features You Don't Use
Turn off automatic transaction enlistment if it's not needed. For the SQL Managed Provider, it's done via the connection string:
SqlConnection conn = new SqlConnection("Server=mysrv01;Integrated Security=true;Enlist=false");
When filling a dataset with the data adapter, don't get primary key information if you don't have to (e.g. don't set MissingSchemaAction.Add with key):
public DataSet SelectSqlSrvRows(DataSet dataset,string connection,string query){
SqlConnection conn = new SqlConnection(connection);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(query, conn);
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(dataset);
return dataset;
}
4.Keep Your Datasets Lean
Only put the records you need into the dataset. Remember that the dataset stores all of its data in memory, and that the more data you request, the longer it will take to transmit across the wire.
5.Use Connection Pooling and Object Pooling
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.