ASP. NET performance tips

Source: Internet
Author: User
Ref: http://weblogs.asp.net/haroonwaheed/archive/2008/06/30/ASP.NET-Performance-Tips.aspx

At times even after applying the best coding protocols ies & practices you don't get the desired level of performance you are hoping from your asp. NET application. this is because there are number other very important factors that directly affect ASP. NET applications. to get the best out of any system requires detail into tural, design, coding and deployment considerations. the post lists few of some of the latest performance tweaks that you can implement to boost up ASP. NET performance.


Remove unused HTTP modules

There are various HTTP modules in ASP. net that intercept each request sent to the server. session state is a very commonly used HTTP module used to load session data in context object. it's referred with sessionstatemodule name. HTTP modules kick in at each request and process them, therefore if you are not using the functionality provided by the module there is no use referring it as they wocould use additional CPU cycles. there is a list of HTTP modules that your application automatically uses when it inherits config setting from web. config placed in $ windowsfolder \ Microsoft. net \ framework \ $ versiosn \ config folder.
Below is a list of such entries:

<Httpmodules>
<Add name = "outputcache" type = "system. Web. caching. outputcachemodule"/>
<Add name = "session" type = "system. Web. sessionstate. sessionstatemodule"/>
<Add name = "windowsauthentication" type = "system. Web. Security. windowsauthenticationmodule"/>
<Add name = "formsauthentication" type = "system. Web. Security. formsauthenticationmodule"/>
<Add name = "passportauthentication" type = "system. Web. Security. passportauthenticationmodule"/>
<Add name = "rolemanager" type = "system. Web. Security. rolemanagermodule"/>
<Add name = "urlauthorization" type = "system. Web. Security. urlauthorizationmodule"/>
<Add name = "fileauthorization" type = "system. Web. Security. fileauthorizationmodule"/>
<Add name = "anonymousidentification" type = "system. Web. Security. anonymousidentificationmodule"/>
<Add name = "Profile" type = "system. Web. profile. profilemodule"/>
<Add name = "errorhandlermodule" type = "system. Web. Mobile. errorhandlermodule, system. Web. Mobile, version = 2.0.0.0, culture = neutral, publickeytoken = b03f5f7f11d50a3a"/>
<Add name = "servicemodel" type = "system. servicemodel. Activation. httpmodule, system. servicemodel, version = 3.0.0.0, culture = neutral, publickeytoken = b77a5c561934e089"/>
</Httpmodules>

There are bunch of HTTP modules listed here and I am quite positive not all of them are being used by your application. removing unused HTTP module can definitely give slight performance boost as there wocould be less work to be performed med. suppose one doesn' t needs Windows Authentication in application. to remove the inherited setting, under httpmodules section in your web. config application Add a remove element and specify name of the module that isn't required.

Example:
<Httpmodules>
<Remove name = "windowsauthentication"/>
</Httpmodules>


<Compilation DEBUG = "true"/> killer

As a developer I have seen numerous incidents were the application is deployed to production with <compilation DEBUG = "true"/>. This is really a performance killer because:

    • Compilation of ASP. NET pages take longer.

    • Code execute slower as debug paths are enabled.

    • More memory is used by the application.

    • Scripts and images from webresource. axd Handler are not cached.

Always make sure that debug flag is set to false on production instances. You can override this by specifying following entry in machine. config for production instances:

<Configuration>
<System. Web>
<Deployment retail = "true"/>
</System. Web>
</Configuration>

This will disable the <compilation DEBUG = "true"/> for all applications deployed on the server.


Turn Off Tracing

Do remember to turn off tracing before deploying application to production. Tracing adds additional overload to your application which is not required in production environment. To disable tracing use the following entries:

<Configuration>
<System. Web>
<Trace enabled = "false"/>
</System. Web>
</Configuration>


Process Model Optimization

ASP. net allows you to define processing process level properties. you can get the detail of all these properties from http://msdn.microsoft.com/en-us/library/7w2sway1.aspx. by default these are set to auto config. this means that ASP. net automatically configures maxworkerthreads, maxiothreads, minfreethreads, minlocalrequestfreethreads and maxconnection to achieve optimal performance. you can tailor these by specifying your own value to achieve better performance. some of the major settings are:

  • Maxworkerthreads. The default value is 20 per process and it determines the maximum number for request that ASP. net can process in a given second. for application that are not CPU intensive and most of time wait on database Request or any external processing this can increased to get better performance.

  • Maxiothreads. The default value is 20 per process and it determines the maximum number for I/O request that ASP. net can process in a given second. if you have enough I/O resources you can increase this value for better results.

  • Memorylimit: The default is 60%. this is the max memory ASP. net can use until worker process is refreshed. if you have a dedicated web server with no other services running you can increase this value for better results.

  • Connectionmanagement: This is a property of system. Net configuration and specifies the maximum parallel connections that can be established to a server. If your web application extensively connects to other server you can increase this value.


Enable Buffering

Make sure that buffering is enabled unless you have a specific need to turn it off. by default its enabled. ASP. net sends response to IIS In a 31 KB buffer which then passes that to the client. when buffering is disabled ASP. net only sends few characters to IIS thus not utilizing this buffer and increasing the trips between IIS and the worker process. to enable it you can change the web. config or enable it on each page through @ page Directive

<Pages buffer = "true">

<% @ Page buffer = "true" %>


Caching

Caching in ASP. net dramatically help in boosting application performance by loading the load on the underlying server and serving cached content that doesn't need to be recreated on each request. ASP. NET provides two types of Caching:

    • Output CacheWhich stores dynamic pages and user controls. One each request code is not executed if a cached version of page or control is available

    • Data CacheWhich allows application to save application objects, dataset etc in server memory so they are not recreated on each request.

Use caching whenever possible to reduce the load on your Web server and to increase response time.

Caching is a huge topic can not be discussed in detail in one post. For more details visit http://msdn.microsoft.com/en-us/library/xsbfdd8c.aspx.


Kernel Cache

Use kernel cache if you are using IIS 6 or above. when output cache is used in ASP. net the request still goes to ASP. net that itself returns the cached content. however if kernel cache is enabled and the request is output cached by ASP. net, IIS versions es the cached content. if a request comes for that data again IIS will serve the cached content and end the response. this can save valuable CPU cycles as it minimizes work saved med by ASP. net.


Avoid using response. Redirect

Instead of using response. redirect, use server. transfer where ever you can. response. redirect sends response to the client which then sends a new request to the server. server. transfer however performs the Redirect on the server. only use response. redirect when you want authentication and authorization to be performed med on redirects or you want URL on client browser to be changed because server. transfer will not do this as it is a server side transfer.


Avoid using server-side validation

Where ever you can use client-side validation instead of server-side validation. this will save you from additional reposts in cases in invalid input. if you don't trust the browsers that they will be able to perform complex validations still use client-side validation and on repost check page. isvalid to check if the input passed the given set of rules.

Avoid databinder. Eval CILS

Avoid calling databinder. eval multiple times for example in case of grids, repeaters etc. instead use continer. databind. databinder. eval uses reflection to evaluate the arguments and therefore can decrease performance if called numerous times.


Avoid using page. databind

Never call page. databind until your really need to do so. instead if you want to bind a specific control only bind that. calling page. databind will call databind for all the controls that support binding.


Viewstate Optimization

Avoid using viewstate for storing huge objects or disable it when you don't need it. viewstate is also used by server controls so that they can retain their state after PostBack. you can also save your objects that are marked serializable in the viewstate. ASP. net serializes all objects and controls in the viewstate and transmits them in a hidden field to the browser. if not managed properly viewstate can increase page size and therefore increase network traffic. also precious CPU cycles are used for serialization and de-serialization of viewstate objects. disable viewstate if:

    • Your Pages don't do PostBack.

    • You controls are not bound to a data source or they don't handle server events like onclick, onselectedindexchanged etc or their properties are set on each PostBack

    • You recreate controls on every PostBack.

You can disable viewstate in both web. config or @ page Directive

<Pages enableviewstate = "false">
Or
<% @ Page enableviewstate = "false" %>


Save or compress viewstate

In case where viewstate in mandatory and the viewstate contains enough data that can cause network congestion or increase download response time for the user try saving or compressing the viewstate. the page class provide two very useful methods loadpagestatefrompersistencemedium () and savepagestatetopersistencemedium (Object viewstate ). you can override these methods to either compress the viewstate or even prevent it from going to the client by saving it in some persistent medium on the server.


Use http Compression

If your page size is large enough to cause noticeable lag between subsequent request and response you can use HTTP compression. HTTP compression is a feature of IIS and what it means is that you can compress data sent to the client using compression techniques like gzip and deflate. on the other side the browser decompresses the data and shows the response to the client. most of the modern browser are capable of handling compressed data. you will certainly get a huge performance boost if your page size is large.

For more details on HTTP compression visit http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/d52ff289-94d3-4085-bc4e-24eb4f312e0e.mspx? MFR = true


Data paging/sorting

When ever using data grid to show data with paging enabled one thing needs to understood that if your query returned let say 5000 record and you are only showing 100 records per page the rest of the 4900 record will be discarding and the same will apply when ever you will change the page or apply sorting. the additional 4900 rows will definitely take up memory and if your database is located on a different server which is most commonly the case you will also be transferring unnecessary data over the network. make sure you are only returning the required results to the ASP. NET application by filtering out the data in your database query and apply custom paging. SQL Server 2005 and onwards provide valuable function for ranking data that can be used to accomplish this.


Connection Pooling

creating a connection to a database is a resource intensive process and takes time. connection pooling allows you to reuse these connections saving time and resources. when a new connection is requested the connection pool managers first searches in the connection pool and if doesn't finds one, it creates a new one. there are varous things that need to be done to use Connection Pooling when tively:

    • Avoid connection leakage. this means that you opened a connection but didn't close it. if you don't close the connection pool manager will never put it in the pool for later reuse until the GC is called.

    • Use the same connection string. connection pool manager searches for similar connection in the pool by the connection string.

    • Use SQL servers and. Net CLR data performance counters to monitor pooling.

    • Open connections as late as possible and close them as early as possible

    • Don't share same connection between multiple function CILS. Instead open a new connection and close it in each function.

    • Close transactions prior to closing the connection.

    • Keep at least one connection open to maintain the connection pool.


Avoid multiple database access

Avoid Accessing Database multiple times for the same request. analyze your code and see if you can reduce the number of trips to database because these trips reduce the number of requests per second your application can serve. you can do this by returning multiple records in the same stored proc, combining multiple dB operations in same stored proc etc.


Use datareader instead of Dataset

Use datareader objects instead of dataset when ever you need to display data. datareader is the most efficient means of data retrieval as they are read and forward only. dataset are disconnected and In-memory therefore uses valuable server resources. only use them when you need the same data more then once or want to do some processing on the data.
Last but certainly not the least follow the best coding, design and deployment patterns and practices. Here are few more usefull links that can be very helpful in performance optimization of you ASP. NET application

    • Http://msdn.microsoft.com/en-us/library/ms973838.aspx

    • Http://msdn.microsoft.com/en-us/library/ms998569.aspx

    • Http://msdn.microsoft.com/en-us/magazine/cc500561.aspx

    • Http://msdn.microsoft.com/en-us/library/ms998549.aspx

    • Http://msdn.microsoft.com/en-us/library/ms973839.aspx

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.