Sunday, May 13, 2007

Improving ASP .NET Performance - Part I

Read a very good, comprehensive article on "Improving ASP .NET Performance" on MSDN. Following are some important and interesting points mentioned in it, particularly concentrating on improving the performance of ASP .NET pages:

1. Trim your page size

Not something that is on our top priority list when we think about improving performance! But large pages increase the response times experienced by the client, increase the consumption of the n/w bandwidth, thereby increasing the load on the CPU. To trim the page size:

a. Remove extra white spaces and tabs (though good coding practice would tell you to keep them for better readability of the code)

b. Use script includes for static javascripts so that they can be cached for subsequent requests.

c. Disable view state when you do not need it

d. Limit the use of graphics, consider using compressed graphics

e. Use CSS for styling to avoid sending same formatting directives to the client repeatedly

f. Avoid long control names! (Again something that is contradictory to good coding pratice rules)

2. Use Page.IsPostBack check in the page code-behind to avoid execution of instructions that need to be executed only once when the page loads for the first time

3. Data Binding in pages:

a. Avoid using Page.DataBind method, since it is a page-level method. It internally invokes DataBind method on all the controls on the page that support data binding. Instead, as far as possible, call DataBind explicitly on required controls.

b. Minimize calls to DataBinder.Eval

DataBinder.Eval uses reflection to evaluate the arguments that are passed to it. This can be quite time consuming and expensive when there are a lot of rows and columns in the table. Instead, one can use explicit casting (cast to DataRowView class) or use ItemDataBound event when the record being bound contains a lot of fields.

4. Partial Page or Fragment Caching

In cases when caching of the entire page is not possible by using the OutputCache directive (this could be the case when parts of the page are dynamic and change frequently), it is possible to enable fragment caching only for specific portions of a page. These portions need to be abstracted out into user controls. The user controls on a page can be cached independently of the page. Typical examples are headers and footers, navigation menus etc.

5. If the same user control is repeated on multiple pages, make the pages share the same instance of the user control by setting the "Shared" attribute of @ OutputCache directive of the user control to true. This will save a significant amount of memory.

No comments: