In this article we will explore some tips for improving ASP.NET performance.
Before starting I would like to request the reader to put some ideas and tips for improving ASP.NET performance.
1. Practices for Data Tier
Database plays a very important role in performance improvement.
- Avoid multiple round trips to database.
- Always use stored procedures
- Avoid using dynamic queries and Cursors.
- Set NoCount ON, unless and until you require the number of rows affected.
- Avoid querying the same table multiple times in a single session/stored procedure.
- Choose properly between Table Variables and Temp Tables.
- Temp Tables are more preferred when the number of records is greater.
- Avoid putting too many indexes into a table.
- If a column is not going to repeat its values, then assign a unique key to it (assuming a primary key is already assigned to some other column).
- Union all is more preferred than Union.
- Avoid writing co-related sub queries like:
Select * from TblEmployee where EmployeeId =(Select EmployeeId from TblAttendance where leaves>1 and EmployeeId= TblEmployee.EmployeeId).
(Try to use a Join instead.)
- If you are sure about the number of rows to be returned by a query, set the Row Count to that number.
Example : Let's say for instance it's 2, then:
set RowCount 2
Select * from TblEmployee where where1=@where1 and where2=@where2
set RowCount 0
2. Paging
Whenever a list of data is needed to be shown, apply paging and show only some records in every page.
3. Layout
Prefer Div Layout over Table Layout. Tables save HTML development time but create performance overhead since the browser must often wait for the whole table to load before it can begin to layout the content.
4. Caching
Try to cache the things which are more on static or will not be changed frequently.
ASP.NET provides substantial support for caching by means of Page Caching and Fragment Caching.
5. Threading
Using threads in an application improves performance by a great extent.
Let's take an example where we can use Threading in ASP.NET.
Consider there is a form with many input fields to be dumped into the database on submit and after that mail must be sent to admin as a success receipt.
With the mail being sent by a separate thread, it is completely independent of the UI rendering.
Note: A thread can be counter-productive if used excessively; in other words, performance will be affected in a reverse manner when a Thread is used excessively.
6. ViewState
It's one of the biggest culprits for performance issues in ASP.NET.
Always disable the ViewState when it's not necessary, like in the case that we have a form filled only with textboxes, the ViewState is not required because, textboxes maintain their values from the postback data regardless of ViewState.
(Please go through the ASP.NET life cycle first.)
Complex controls like a GridView maintains a very large amount of ViewState, better disable it and rebind it when it's required.
7. SessionState
- Do not overuse Session State for user data storage.
- Choose proper session state (InProc, OutProc).
- Avoid storing complex objects into sessions because such things involve serialization and deserialization internally which results in a big performance penalty.
- If a session variable is no longer required then clear it.
Note:
- ViewState is used to store Page-specific data whereas Session is used to store user-specific (in other words, stored in server memory).
- More things in ViewState means slow page, more things in session means slow website.
- The above statement doesn't mean we should go with ViewState always, it's up to the environment and condition.
For example consider we have to store a huge amount of data but the website is not going to be accessed by many users; there might be one to three users that will access it simultaneously. In this case the session will be worthwhile.
If you try ViewState for such huge objects pages then it can get extremely heavy and might not even load.
8. Set retail="true" in your machine.config
<configuration>
<system.web>
<deployment retail="true"/>
</system.web>
</configuration>
- It will force the "debug" flag in the web.config to be false.
- It will disable page output tracing.
- It will force the custom error page to be shown to remote users rather than the actual exception or error message.
9. Use HTML controls whenever possible
ASP.NET server controls renders them according to the browser capabilities and if required write some JavaScript also, so use HTML controls whenever possible.
One scenario is if there are some controls which are never going to be accessed from the server side then it is better to make them HTML controls.
10. Postback
Avoid unnecessary postback to the server whenever possible.
One scenario is, a postback is not required for just validating empty text, we can do that even using JavaScript.
11. Page.IsPostBack
Use Page.IsPostBack to avoid performing unnecessary processing on a postback.
12. Exception handling
Try to avoid Try...Catch block , instead try to avoid exceptions using If…else.
Example
Try
{
//Read A
//Read B
//Return A/B
}
Catch(DevidebyZeroException e)
{
//B is zero please provide something else
}
Can be replaced with
//Read A
//Read B
//If (B==0){Please provide some other value}.
//else return A/B
13. ListView instead of GridView
As automation increases, performance decreases, becuase sometimes we use many things that are not required.
GridView provides automatic structure in a table format whereas a ListView can be used to create our own structure in a productive manner.
StringBuilder
Choose wisely between string and StringBuilder.
Only if a string will be manipulated more than twice use a StringBuilder or else string is preferred.
14. Server.Transfer
If navigation to a page is necessary in the same application then use Server.Transfer instead of Response.Redirect.
15. Remove Unnecessary modules
ASP.NET has many default Http Modules in its request pipeline, each for doing a specific task.
Example: SessionStateModule intercepts each request, parses the session cookie and then loads the proper session in the context.
There are many modules like FormAuthentication, WindowsAuthentication, Membership And Profile provider and even SessionStateModule which are usually not required. (For instance, if we are not using Windows Authentication then the corresponding module is also not required).
These modules are just sitting in the pipeline, executing some unnecessary code for each and every request.
Now to remove these default modules from your Web application, simply add <remove> nodes in your site's Web.Config.
<httpmodules>
<remove name=""WindowsAuthentication"" />
<remove name=""PassportAuthentication"" />
<remove name=""AnonymousIdentification"" />
<remove name=""UrlAuthorization"" />
<remove name=""FileAuthorization"" />
</httpmodules>
16. Ajax
Using Ajax in our applications dramatically increases the performance, as it gets the data without making a complete postback.
There are various mechanisms for performing Ajax calls in ASP.NET like PageMethods, using jqury $.ajax or even ASP.NET update Panel.
PageMethods and $.ajax works faster than UpdatePanel, but you won't be able to access control values when working with those.
17. Clean up resources
Always clean up your resources once it completes its purpose.
(Use proper use of IDisposable interface in you custom business classes.)
18. Choose Generics instead of collections and arrays
- Arrays - Fixed Size and Type Safe.
- ArrayList - Dynamic Size but not Type Safe.
- Generic List - Dynamic Size and Type Safe.
Generics improve performance over Collections as implicit boxing and explicit unboxing are not needed.
19. CSS and JS
Never use inline or internal CSS, use external.
The same applies to JS.
(When we include external CSS/JS in the page it is cached and so won't download on every request. Two birds in a single shot Performance and Management.)
20. 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 modern browsers are capable of handling compressed data. You will certainly get a huge performance boost if your page size is large.
http://www.iis.net/ConfigReference/system.webServer/httpCompression
Hope you enjoyed reading this article,
I want you guys to share some more tips and thoughts related to performance.
If we share then only we can learn, I really appreciate to see some more good comments.
Click here to read Best Practices for ASP.NET.