Web application is designed to handle hundreds and thousands of requests per seconds so to handle these requests effectively and successfully it is important to resolve any potential performance bottlenecks. Now we will state some tips that improve the performance of your web application. Try HostForLife.eu, only with € 3.00/month, you can get a reasonable price with best service. This topic contains only brief information about ASP.NET, if you want to be more familiar with ASP.NET, you should try HostForLife.eu.

1. Cache Commonly used objects
You can cache commonly used objects in ASP.Net using Cache class that provides an extensive caching mechanism that storing resources and allow you to:

- Define an expiration for a cached object either by specified a TimeSpan or a fixed DateTime.

- Define priority for cached objects. when there is a memory lack and objects need to be freed.

- Define validity for a cached object by adding dependacies

- Attach callbacks to cached objects,so when an objects is removed from cache the callback is invoked.

you can add objects to cache by adding it to cache Dictionary.

Cache["Mykey"] = myObject;

or using Insert method of Cache class

Cache.Insert("MyKey",myObject, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(60), dependacies : null );

2. Using Asynchronous Pages,Modules and Controllers
When IIS passes a request to ASP.NET, the request is queued to the thread pool and a worker thread is assigned to handle this request. the worker thread is limited so any new request will be queued to be handle after the current requests handled. If a request need to do some I/O operation like retrieving data from  a database or calling web service that mean you need to reduce the request time.

You can change I/O operation in your web page by making it as Asynchronous Page. In ASP.NET you can do that by firstly marking the page as async

<%@ Page Async="true"....

then create new PageAsyncTask object and pass it the delegates for the begin, end, and timeout methods. After creating PageAsyncTask object, call the Page.RegisterAsuncTask method to start the asynchronous opertaion.

public partial class MyAsyncPage : System.Web.UI.Page
{
   private SqlConnection _sqlConnection;
   private SqlCommand _sqlCommand;
   private SqlDataReader _sqlReader;

   IAsyncResult BeginAsyncOp(Object sender, EventArgs e, AsyncCallback cb, Object state)
   {
       // this method will be executed in the original worker thread,
       //so don't do any lengthy operation here
       _sqlcommand = CreateSqlCommand(_sqlConnection);
       return _sqlCommand.BeginExecuteReader();
   }
   void EndAsyncOp(IAsyncResult asyncResult)
   {
       _sqlReader = _sqlCommand.EndExecuteReader(asyncResult);
       // read the data and build page contents
       .............
   }
   void TimeoutAsyncOp(IAsyncResult asyncResult)
   {
       _sqlReader = _sqlCommand.EndExecuteReader(asyncResult);
       // read the data and build page contents
       .............
   }
   public override void Dispose()
   {
       if(_sqlConnection != null)
       {
           _sqlConnection.Close();
       }
   }
   protected void btnClick_Click(Object sender, EventArgs e)
   {
       PageAsyncTask task = new PageAsyncTask( new BeginEventHandler(BeginAsyncOp),
                                               new EndEventHandler(EndAsyncOp),
                                               new TimeoutEventHandler(TimeoutAsyncOp),
                                               state : null);
       RegisterAsyncTask(task);
   }
}

There is another way to create async pages is by using completion events.

public partial class MyAsyncPage2 : System.Web.UI.Page
{
   protected void btnGetData_Click(Object sender , EventArgs e)
   {
       Services.MyService serviceProxy = new Services.MyService();
       serviceProxy.GetDataCompleted +=Services.GetDataCompletedEventHandler(GetData_Completed);
       serviceProxy.GetDataAsync();
   }
   void GetData_Completed(Object sender,Services.GetDataCompletedEventArgs e)
   {
       //Extract the result from the event args and build the page's content
   }

}

In ASP.NET MVC you can create such mechanisme by creating Asynchronous Controller. To create such contoller you need to follow these four steps:

- Create a Controller class that inherits from the AsyncController type.

- Implement  a set of action methods for each async operation according to the following convention, where xx is the name of the action: xxAsync and xxCompleted.

- In the xxAsync method, call the AsyncManager.OutstandingOperations.Increment method with the number of asynchronous operations you are about to perform.

- In the code which executes during the return of the async operation, call the AsyncManager.OutstandingOperations.Decrement method to notify the operation has completed.

The following code shows you how to implement these steps:

public class MyController : AsyncController
{
   public void IndexAsync()
   {
       AsyncManager.OutStandingOperations.Increment();      
       MyService serviceProxy = new MyService();
       serviceProxy.GetDataCompleted += (sender , e) => {
                                        AsyncManager.Parameters["result"] = e.Value;
                                        AsyncManager.OutStandingOperations.Decrement();
                                        };
       serviceProxy.GetHeadlinesAsync();
   }
   public ActionResult IndexCompleted(MyData result)
   {
       return view("Index",new MyViewModel { TheData = result });
   }
}

3. Turn off ASP.NET Tracing and debugging
before deploying your web application turn of tracing feature by setting it to false in web.config file

<configuration>
    <system.web>
        <trace enabled="false" />
    </system.web>
</configuration>

While development phase you need to enable debugger to debug your code by setting it to true in web.config file. Neglecting change it again to false before deploying will affect your web application performance by facing many problems:

- Scripts that are downloaded using the WebResources.axd handler, by setting debug to false responses from that handler will be returned with caching headers, allowing browsers to cache the responses for future use.

- Request will not timeout when debug is set to true. By setting it to false will enable ASP.NET to define timeouts for requests according to the HttpRuntime.Execution Timeout configuration settings.

- JIT optimization will not be applied to the code when running with debug = true. JIT can efficiently improve the performance of your ASP.NET application without requiring you change your code.

- The compilation process does not use batch compilation when using debug = true. without batch compilation an assembly will be created for each page and control causing web application to load so many of assemblies during runtime. When debug set to false batch compilation is used, generating a single assembly for the user control and a several assemblies for pages.

in case you fear to forget setting debug to false when deploying your application, you can force all ASP.NET applications in a server to ignore the debug setting by adding  the following configurations in the server's machine.config file.

<configuration>
    <system.web>
        <deployment retail="true" />
    </system.web>
</configuration>

4. Disable View State
View state is used to allow ASP.NET to keep the state of the page between postbacks performed by user. View state data is stored in HTML output inside hidden field. If your page displays many controls that contains a huge data, the view state field will be big enough to affect the response time of your page. if your page just display data without need any postback so it will be better to disable the view state of the whole page by set EnableViewState to false.

<%@ Page EnableViewState="false".......%>

or disable view state of some controls in your page

<Asp:GridView ID="MyGrid" runat="server" DataSource="MyDataSource" EnableViewState="false" />

if you don't want to use view state in all pages of your web application it recommended to disable view state for whole web application by setting it to false in your web.config file

<system.web>
    <pages enableViewState="false" ....../>
</system.web>

5. Pre-Compiling ASP.NET Application
When compiling an ASP.NET application project, a single assembly is created to hold all application's code but web pages(.aspx) and user controls(.ascx) not compiled and be deployed as it is. In the first request ASP.NET dynamically compiles the web pages and user control and places the compiled files in the ASP.NET temporary files folder.
To reduce the time of first request the web application can be pre-compiled, including all code, pages, and user controls, by using the ASP.NET compilation tool (Aspnet_compiler.exe). Running this tool in production servers can reduce the delay users experience on first requests.

- Open a command prompt in your production server.

- Navigate to the %windir%\Microsoft.Net folder

- Navigate to either the Framework or Framework64 according to the configuration of web application's application pool.

- Navigate to framework version's folder.

- Enter the following command to start the compilation

Aspnet_compiler.exe  -v  /FullPathOfYourWebApplication