Tuning, Optimizing, Increasing and Improving Performance of Asp.Net Application - Part II
Technical
Posted on Saturday, January 23, 2010 8:19:43 PM
and it has been read 7873 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.
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.
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.
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.
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.
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.
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;
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.
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");
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.
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.
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.
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.
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."
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.