Blog Post by Murat Yaşar


Posted on Saturday, January 23, 2010 8:19:43 PM and it has been read 3328 times since then.


Tuning, Optimizing, Increasing and Improving Performance of Asp.Net Application - Part II

I gathered things together from the internet that is why also specified as many links as possible. This is kind of check list to get benefit from. I gave the original link for each item in this list to their author's web site.

You can reach other two blog entries which are also part of this series from the following links:
In this entry, I will be focusing on the web.config file...
In this entry, I will be focusing on the MS SQL Server and T-SQL...

In the second part of this three-part series, I will try to give you some of the precautions that we had better pay attention in markup and code behind file before going public with our asp.net application. I just wanted to give you kind of check list which consists of as many item as possibly could be in it. In this part, I will be focusing on the code behind file and markup, some tips and best practices I gathered from my reading on the internet. If you think that some other unique links (I believe there are) available and would be beneficial to others, please share them as a comment.


Part II : Markup and Coding


1-) ScriptMode for Release
Try to make script mode always release for better performance.

<asp:ScriptManager ID="ScriptManager1" runat="server" ScriptMode="Release">
</asp:ScriptManager>

Take a look at this link to get more information:
http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.scriptmode.aspx


2-) CompositeScript
If you are using ASP.NET 3.5 with SP1, there is a more powerful tool to combining the Script file with CompositeScript feature.

First, we can use the ScriptReferenceProfiler to show the JavaScript references and then, we can add <CompositeScript> and <Scripts> elements as children of the ScriptManager control.

If you have watched this video, you must probably know <microsoft:ScriptReferenceProfiler> and how helpful this control for understanding which scripts gets loaded when you load the page.

After seeing the script references from the page and paste them into the <Scripts> element inside the ScriptManager control, the result will be a single request for all the script references.

Take a look at these links to get more information:
http://lancezhang.wordpress.com/2008/11/15/aspnet-ajax-performance/
http://msdn.microsoft.com/en-us/library/cc488552.aspx
http://bellouti.wordpress.com/2008/09/14/combining-javascript-files-with-ajax-toolkit-library/

An issue to be aware of...
http://julianjelfs.wordpress.com/2009/04/16/scriptmanagercompositescript-issues/


3-) LoadScriptBeforeUI
ScriptManager control has LoadScriptsBeforeUI property which we can set to "False" in order to postpone several script downloads until the content is downloaded and shown. This adds the script references end of the <body> tag. As a result, we will see the content first and then the additional scripts, extenders, AJAX Control Toolkit scripts get downloaded and initialized.
This will make the page show quickly, and provide a better User Experience.

Take a look at these links to get more information:
http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.loadscriptsbeforeui.aspx
http://weblogs.asp.net/infinitiesloop/archive/2007/03/03/scriptmanager-loadscriptsbeforeui-explained.aspx


4-) EnablePartialRendering Yes or No?
There is another property in ScriptManager named EnablePartialRendering, it gets or sets a value that enables partial rendering of a page, which in turn enables you to update regions of the page individually by using UpdatePanel controls.

So, if we are using the UpdatePanel in the page, we must set this property to true, conversely, if the UpdatePanel is not using in our page, it would be better that we set the EnablePartialRendering to false. That will cause the unnecessary file "MicrosoftAjaxWebForm.js", which is used to the partial rendering not import to our page.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="false">
</asp:ScriptManager>

Take a look at this link to get more information:
http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.enablepartialrendering.aspx
http://weblogs.asp.net/leftslipper/scriptmanager-s-enablepartialrendering-and-supportspartialrendering-properties


5-) Think about css sprites.

Take a look at the following link to get more information:
http://www.alistapart.com/articles/sprites


6-) Use Response.Redirect (".aspx",false) instead of response.redirect(".aspx"). It Reduces CLR Exceptions count.

Take a look at these links to get more information:
http://support.microsoft.com/kb/312629
http://msdn.microsoft.com/en-us/library/a8wa7sdt.aspx


7-) Use the AppOffline.htm when updating binaries. (Applicable only .Net Framework 2.0 and above)
If you want to show the users a user friendly page instead of showing them an ugly error page while updating your binaries use AppOffline.htm file. It is easy and user friendly.

Take a look at the following link to get more information:
http://weblogs.asp.net/scottgu/App_5F00_Offline.htm-and-working-around-the-_2200_IE-Friendly-Errors_2200_-feature


8-) Use Caching to improve the performance of your application.

Take a look at these links to get more information:
http://msdn.microsoft.com/en-us/library/xsbfdd8c.aspx
http://weblogs.asp.net/scottgu/tip-trick-implement-donut-caching-with-the-asp-net-2-0-output-cache-substitution-feature


9-) Avoid exceptions and use if condition.
Exceptions are probably one of the heaviest resource hogs and causes of slowdowns you will ever see in web applications, as well as windows applications.

You can use as many try/catch blocks as you want but using exceptions gratuitously is where you lose performance.

Since exceptions cause performance to suffer significantly, you should never use them as a way to control normal program flow. If it is possible to detect in code a condition that would cause an exception, you should do that instead of waiting to catch the exception itself before handling that condition. Common scenarios include checking for null, assigning to a string that will be parsed into a numeric value, or checking for specific values before applying math operations. The following example demonstrates code that could cause an exception, and you to test for a condition that would do the same thing.

// consider changing this...

try {
  result = 100 / num;
}
catch( Exception e ) {
  result = 0;
}

// to this...

if ( num != 0 )
   result = 100 / num;
else
   result = 0;

Take a look at these links to get more information:
http://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET
http://www.dotnetfunda.com/articles/show/45/best-practices-to-improve-aspnet-web-application-performance


10-) Avoid using code like x = x +1; it is always better to use x+=1.


11-) Use finally method to kill resources.
The finally method gets executed independent of the outcome of the block.
Always use the finally block to kill resources like closing database connection, closing files and other resources such that they get executed independent of whether the code worked in Try or went to Catch.


12-) 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.

Take a look at the following link to get more information:
https://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx


13-) Manage View State

Take a look at the following link to get more information:
http://www.w3schools.com/aspnet/aspnet_viewstate.asp


14-) Use Async pages for IO bound operations.

Take a look at these links to get more information:
https://msdn.microsoft.com/en-us/magazine/cc163725.aspx
https://msdn.microsoft.com/en-us/library/system.web.ui.pageasynctask.aspx


15-) Leverage JavaScript frameworks such as jQuery

Take a look at the following link to get more information:
http://blogs.msdn.com/b/timchen/archive/2009/03/03/why-use-jquery-in-your-asp-net-web-app.aspx


16-) Watch your server roundtrips.
When we use Response.Redirect to move from one page to another we ideally also call HTTP 302 Found. This increases extra trip. Now in Visual Studio 2010 you may write Response.RedirectPermanent("Page1.aspx");

Take a look at these links to get more information:
https://msdn.microsoft.com/en-us/library/system.web.httpresponse.redirectpermanent(VS.100).aspx
http://www.haiders.net/post/ResponseRedirectPermanent.aspx
http://weblogs.asp.net/gunnarpeipman/asp-net-4-0-seo-features-response-permanentredirect
http://www.dascode.net/post/2009/09/21/C-40-ResponseRedirectPermanent.aspx


17-) Caching at various level is equally important (Page level, data etc.)
Caching is a technique widely used in computing to increase performance by keeping frequently accessed or expensive data in memory. In context of web application, caching is used to retain the pages or data across HTTP requests and reuse them without the expense of recreating them. ASP.NET has 3 kinds of caching strategies Output Caching, Fragment Caching, Data Caching.

Output Caching: Caches the dynamic output generated by a request. Some times it is useful to cache  the output of a website even for a minute, which will result in a better  performance. For caching the whole page the page should have OutputCache directive.

<%@ OutputCache Duration="60" VaryByParam="state" %>

Fragment Caching: Caches the portion of the page generated by the request. Some times it is not practical to cache the entire page, in such cases we can cache a portion of page.

<%@ OutputCache Duration="120" VaryByParam="CategoryID;SelectedID"%>

https://support.microsoft.com/en-us/kb/308378/

Data Caching: Caches the objects programmatically. For data caching asp.net provides a cache object for eg: cache["States"] = dsStates;


18-) Using Ajax to fetch data "on demand" and cache locally as XML (XML data islands etc.)

Take a look at the following link to get more information:
https://www.redhat.com/f/pdf/exadel/AjaxOnDemandWP.pdf


19-) If you are using asp.net 2.0 or higher version then always use precompiled version of your code and also prefer web application project over website. If you are using website then always publish it and then upload that precompiled version of your site into production environment.

When you precompile your web application the following takes place:
- All markup files (.aspx) are stripped of their content
- All web service files (.asmx) are stripped of their content
- All code-behind files (.cs) are removed
- All user control files (.ascx) are removed

This means that you will be able to deploy your website entirely without readable markup or source code. You still need all the markup files in the correct places, but they will no longer contain any actual markup.

Take a look at these links to get more information:
https://msdn.microsoft.com/en-us/library/bb398860.aspx
https://msdn.microsoft.com/en-us/library/ms227972.aspx
https://msdn.microsoft.com/en-us/library/ms227976.aspx
http://www.devx.com/dotnet/Article/34418


20-) Decrease your html kb as much as you can. In order to do that use tableless html using divs and if possible do not give big name to your control. It will increase your html kb as asp.net uses client Id to differentiate all the controls. If you are creating custom controls then you can overwrite your clientid and uniqueId.


21-) Remove blank spaces from your html. It will increase your kb.


22-) For asp.net 2.0 and higher version use master pages. It will increase your performance.

Take a look at these links to get more information:
https://msdn.microsoft.com/en-us/library/wtxbf3hh.aspx
http://webproject.scottgu.com/CSharp/MasterPages/MasterPages.aspx
http://www.aspfree.com/c/a/ASP.NET/How-to-Use-Master-Pages/


23-) Disable view state for your controls if possible. If you are using asp.net 2.0 or higher version then use asp.net control state instead of view state. Store view state in session or database by overriding the default methods for storing view state.
MSDN says "Use control state only for small amounts of critical data that are essential for the control across postbacks. Do not use control state as an alternative to view state."

Take a look at these links to get more information:
https://msdn.microsoft.com/en-us/library/1whwt1k7.aspx
https://msdn.microsoft.com/en-us/magazine/cc163901.aspx
http://codeasp.net/articles/ASP.NET/39/asp.net-viewstate-and-control-state


24-) Use Ajax for your application wisely. Lots of Ajax calls for a page will also decrease your performance.

Take a look at these links to get more information:
http://webdesign.about.com/od/ajax/a/aa092506.htm
http://www.noupe.com/design/how-ajax-works.html
http://blog.adriaandejonge.eu/2005/07/when-not-to-use-ajax.html


25-) Use  System.Text.StringBuilder for string concatenation but not always. Check out the following links for more info.

Take a look at these links to get more information:
http://www.hanselman.com/blog/StringBuildersVsStringConcatenation.aspx
http://www.codeproject.com/KB/cs/stringperf.aspx?fid=179078&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=1103916&fr=26


26-) Call web service from javascript instead of server side. Use asynchronous calls to call a web method from web service.

Take a look at these links to get more information:
http://blogs.msdn.com/b/kaevans/archive/2008/04/03/calling-webservices-via-ajax-part-1.aspx
http://www.geekzilla.co.uk/View7B75C93E-C8C9-4576-972B-2C3138DFC671.htm


27-) Use client-side validation. A client-side script is a script that is included in a page's HTML and is executed on the client based on user events. Using a client-side script means the browser doesn't have to make a round-trip to the server to perform routine client-side tasks. For example, you wouldn't want to send the browser to the server to validate that all of the required fields on a form were filled out.

Take a look at the following link to get more information:
https://msdn.microsoft.com/en-us/library/yb52a4x0.aspx


28-) Inline css classes could make HTML heavy. Go ahead with a single css file.

Take a look at the following link to get more information:
http://robertnyman.com/2008/11/20/why-inline-css-and-javascript-code-is-such-a-bad-thing/


29-) Write static messages in div and make it visible when necessary. This is faster than letting server set text property of your label or div.


30-) Reduce cookie size
There is a condition that occurs on many networks limiting the packet size to just 1,500 bytes. Big cookie, plus a 500 or so byte header means extra work for the user, the network, and your server. The basic lesson from this is to keep your cookies streamlined and small. Limit cookie size by only storing the most essential data.

Take a look at these links to get more information:
http://yuiblog.com/blog/2007/03/01/performance-research-part-3/
https://developer.yahoo.com/performance/rules.html#cookie_size


31-) With images, reduce the number of colors, and compress.

Take a look at the following link to get more information:
http://www.webdevelopersnotes.com/graphics/decreasing_web_images_size.php3


32-) For images use JPG, PNG, and GIF if the image is less than 100 square pixels. Avoid TIFF and BMP.

Take a look at the following link to get more information:
http://www.quickonlinetips.com/archives/2009/08/optimizing-images/


33-) Never use object value directly; first get object value in local variable and then use. It takes more time then variable reading.

Objects are expensive to use, partly because of the overhead involved in allocating memory from the heap (which is actually well-optimized in .NET) and partly because every created object must eventually be destroyed. The destruction of an object may take longer than its creation and initialization, especially if the class contains a custom finalization routine. Also, the garbage collector runs in an indeterministic way; there's no guarantee that an object's memory will be immediately reclaimed when it goes out of scope, and until it's collected, this wasted memory can adversely affect performance.


34-) Inline JavaScript could make the HTML page heavy, so it's preferred to serve separate .js files or a single JavaScript file to keep all JavaScript-based scripts in a single place.


35-) Separate JavaScript files also get cached automatically by browsers, so they usually aren't requested each time the page is loaded by the browsers.


36-) If you have to place a background image, some large image or a screenshot then the suggested format is JPG/JPEG.


37-) If you have to use small graphics like button images, header images, footer images, navigation bar images or clip arts, then the suggested format is PNG.


38-) If an image is not required to be in high or true colors and 256 colors are enough, then GIF is preferred.


39-) The recommended approach is to put CSS links on top of the web page, as it makes the page render progressively efficient. Since users want to see the contents of a page whilst it's loading rather than white spaces, contents/formats should be given on top. HTML Specifications clearly say to declare style sheets in the head section of a web page.

Take a look at the following link to get more information:
https://developer.yahoo.com/performance/rules.html#css_top


40-) Use Content Delivery Network (CDN)
As your web site grows ever more popular, sometimes the best way to get a performance boost is to let somebody else handle delivery of your resource files these are your static images, scripts, movies, SWF files, etc. One option is to purchase more bandwidth from your supplier. Another is to enlist the support of a Content Delivery Network kind of like a private, global internet with public endpoints close to your customers.

The benefit of a CDN is that you are effectively outsourcing the delivery of your static files onto another "usually much faster" network. Often this will result in an ability for your server to handle more connections than before, since it no longer has to worry about serving up the big files over and over again.

Take a look at these links to get more information:
https://developer.yahoo.com/performance/rules.html#cdn
https://developer.yahoo.com/performance/rules.html


41-) When using ASP.NET AJAX and the UpdatePanel control for partial page rendering, use the maximum number of update panels to update small chunks of page, but use them wisely. Don't set the Update property to Always unless needed. Instead, set the update mode to Conditional, otherwise all the partial chunks would be sent together after each asynchronous postback.

Take a look at these links to get more information:
https://msdn.microsoft.com/en-us/magazine/cc163413.aspx
http://encosia.com/why-aspnet-ajax-updatepanels-are-dangerous/


42-) Ajax based requests can also be cached when using the GET method. If the URL is the same, then cached data can be used from the client, and a round trip to the server can be avoided. Preferably use the GET method for Ajax based Requests, because if you use POST method then the request header would be sent first, followed by the data, which basically splits the request in two steps. A single-step request can be achieved with GET if a cookie is not too long and the URL is not larger than 2k.

Take a look at the following link to get more information:
https://developer.yahoo.com/performance/rules.html#ajax_get


43-) Use Output Buffering
By default its enabled. ASP.Net sends response to IIS in a 31 KB buffer, which is then passed to the client. When buffering is disabled, ASP.NET only sends few characters to IIS, thus not utilizing this buffer. Which in turn increases the trips between IIS and the worker process. To enable it you can change the web.config or you can enable it on each page through @page directive.

MSDN talks about it here:
https://msdn.microsoft.com/en-us/library/ms998549.aspx
Reduce round trips when possible by buffering your output. This approach batches work on the server and avoids chatty communication with the client. The downside is that the client does not see any rendering of the page until it is complete. You can use the Response.Flush method. This method sends output up to that point to the client. Note that clients that connect over slow networks where buffering is turned off, affect the response time of your server. The response time of your server is affected because your server needs to wait for acknowledgements from the client. The acknowledgements from the client occur after the client receives all the content from the server.


44-) Use Repeater Control And Avoid DataList, DataGrid, and DataView controls.

Take a look at the following link to get more information:
http://stackoverflow.com/questions/139207/repeater-listview-datalist-datagrid-gridview-which-to-choose/139308#139308


45-) Take advantage of HttpResponse.IsClientConnected, before performing a large operation. The IsClientConnected property returns True if the client is still connected to the Web server during the processing of a response.

Take a look at the following link to get more information:
https://msdn.microsoft.com/en-us/library/system.web.httpresponse.isclientconnected.aspx


46-) Use HTTPServerUtility.Transfer instead of Response.Redirect
Response.Redirect should only be used when you are transferring people to another physical web server.  For any transfers within your server, use HTTPServerUtility.Transfer. You will save a lot of needless HTTP requests. Response.Redirect sends response to the client which then sends a new request to the server. HTTPServerUtility.Transfer however performs the redirect on the server. Only use Response.Redirect when you want authentication and authorization to be performed on redirects or you want URL on client browser to be changed because HTTPServerUtility.Transfer will not do this as it is a server side transfer.


47-) Always check Page.IsValid when using Validator Controls.
So you've dropped on some validator controls, and you think you are good to go because ASP.net does everything for you!  Right? Wrong!  All that happens if bad data is received is the IsValid flag is set to false. So make sure you check Page.IsValid before processing your forms! If you don't trust the browsers that they will be able to perform complex validations you can still use client-side validation and on repost check Page.IsValid to check if the input passed the given set of rules.


48-) Use the AddRange() Method with Collections
There is a large number of collection classes that expose the AddRange() method. You can use this to add an array of items to the collection instead of calling the Add() method repeatedly inside a loop.

Take a look at these links to get more information:
http://geekswithblogs.net/sdorman/archive/2007/09/21/Add-vs.-AddRange.aspx
http://windevblog.blogspot.com.tr/2008/09/fastest-way-to-fill-listview-control.html


49-) Avoid Frequent Usage of Boxing and Unboxing
When a value type, such as a structure, is copied to a reference type such as a class, the compiler creates an object on the heap and copies the value of the value type from the stack to this newly created object on the heap. This process is called boxing and requires more overhead than just a simple from value type to value type. When you copy a reference type to a value type, the value of the object from the heap is copied to the value type from the stack. This process is called unboxing. You should take in consideration the overhead of these processes when you design your application.


50-) Avoid Using Unmanaged Code
Calls to unmanaged code are a costly marshaling operation. Try to reduce the number of calls between the managed and unmanaged code. Consider doing more work in each call rather than making frequent calls to do small tasks.


51-) Encode Using ASCII When You Don't Need UTF
By default, ASP.NET comes configured to encode requests and responses as UTF-8. If ASCII is all your application needs, eliminated the UTF overhead can give you back a few cycles. Note that this can only be done on a per-application basis.


52-) 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.


53-) An additional tip to reduce page processing is to avoid web controls all together. Don't use ASP.NET web controls for static information. Stick to the generic HTML controls that we all knew and love before ASP.NET was ever invented.


54-) Using CSS instead of tables will cause the browser to render your pages faster. Tableless design.

Take a look at the following link to get more information:
http://en.wikipedia.org/wiki/Tableless_web_design


55-) Improve bandwith performance using IIS compression.

You can check whether or not your current web site is using IIS compression from the following link.
http://www.whatsmyip.org/http-compression-test/


56-) As always, avoid session variables because each ASP page runs in a different thread and session calls will be serialized one by one. So, this will slow down the application. Instead of session variables you can use the QueryString collection or hidden variables in the form which holds the values.


57-) Use single css file instead of multiple css file. Try your best to combine all your CSS based classes into a single css file as lots of css files will cause a large amount of requests, regardless of the file sizes. Css files are normally cached by browsers, so a single and heavy css file doesn't cause a long wait on each page request. Inline css classes could make HTML heavy, so again go ahead with a single css file.


58-) Compress CSS, JavaScript and Images
Online compressors are available; to compress file please refer to following link and replace your file content with optimize code.
http://iceyboard.no-ip.org/projects/css_compressor for CSS compression
http://www.xtreeme.com/javascript-optimizer/  for JS Compression


59-) Use using statement.

Take a look at the following link to get more information:
https://msdn.microsoft.com/en-us/library/yh598w02.aspx


60-) Don't make the member variables public or protected, try to keep private and use public/protected as properties.


61-) Use strString = string.Empty instead of strString = "" .

Take a look at the following link to get more information:
http://blogs.msdn.com/b/brada/archive/2003/04/22/49997.aspx


62-) Use short ID name for WebControl. If you use long name, it will increase the rendered HTML page size.


63-) Consider caching of images.

Take a look at the following link to get more information:
http://www.codeproject.com/Articles/22888/Caching-Images-in-ASP-NET



I will be updating this entry if there is any new option to consider as well as a new link which explains better the option we are talking on.

Have a great day.


(In order to use this feature, you have to register.)

Tag Related Blog Entries