SlideShare una empresa de Scribd logo
1 de 9
ASP.NET Best Practices for High
Performance Applications
By Ali Khan (OKC), 21 Mar 2006
4.65 (165 votes)

Introduction
ASP.NET is much more powerful than classic ASP, however it is important to understand
how to use that power to build highly efficient, reliable and robust applications. In this article,
I tried to highlight the key tips you can use to maximize the performance of your ASP.NET
pages. The list can be much longer, I am only emphasizing the most important ones.

1. Plan and research before you develop
Research and investigate how .NET can really benefit you. .NET offers a variety of solutions
on each level of application design and development. It is imperative that you understand
your situation and pros and cons of each approach supported by this rich development
environment. Visual Studio is a comprehensive development package and offers many
options to implement the same logic. It is really important that you examine each option and
find the best optimal solution suited for the task at hand. Use layering to logically partition
your application logic into presentation, business, and data access layers. It will not only help
you create maintainable code, but also permits you to monitor and optimize the performance
of each layer separately. A clear logical separation also offers more choices for scaling your
application. Try to reduce the amount of code in your code-behind files to improve
maintenance and scalability.

2. String concatenation
If not handled properly, String Concatenation can really decrease the performance of your
application. You can concatenate strings in two ways.
First, by using string and adding the new string to an existing string. However, this
operation is really expensive (especially if you are concatenating the string within a
loop). When you add a string to an existing string, the Framework copies both the
existing and new data to the memory, deletes the existing string, and reads data in a
new string. This operation can be very time consuming and costly in lengthy string
concatenation operations.
The second and better way to concatenate strings is using the StringBuilder Class.
Below is an example of both approaches. If you are considering doing any type of
String Concatenation, please do yourself a favor and test both routines separately.
You may be surprised at the results.
Collapse | Copy Code
'Concatenation using String Class
Response.Write("<b>String Class</b>")
Dim str As String = ""
Dim startTime As DateTime = DateTime.Now
Response.Write(("<br>Start time:" + startTime.ToString()))
Dim i As Integer
For i = 0 To 99999
str += i.ToString()
Next i
Dim EndTime As DateTime = DateTime.Now
Response.Write(("<br>End time:" + EndTime.ToString()))
Response.Write(("<br># of time Concatenated: " + i.ToString))

Results: Took 4 minutes and 23 Seconds to to complete 100,000 Concatenations.
String
o
o
o

Class
Start time: 2/15/2006 10:21:24 AM
End time: 2/15/2006 10:25:47 AM
# of time Concatenated: 100000

Collapse | Copy Code
'Concatenation using StringBuilder
Response.Write("<b>StringBuilder Class</b>")
Dim strbuilder As New StringBuilder()
Dim startTime As DateTime = DateTime.Now
Response.Write(("<br>Start time:" + startTime.ToString()))
Dim i As Integer
For i = 0 To 99999
strbuilder.Append(i.ToString())
Next i
Dim EndTime As DateTime = DateTime.Now
Response.Write(("<br>Stop time:" + EndTime.ToString()))
Response.Write(("<br># of time Concatenated: " + i.ToString))

Results: Took less than a Second to complete 100,000 Concatenations.
StringBuilder
o
o
o

Class

Start time: 2/15/2006 10:31:22 AM
Stop time:2/15/2006 10:31:22 AM
# of time Concatenated: 100000

This is one of the many situations in which ASP.NET provides extremely high performance
benefits over classic ASP.

3. Avoid round trips to the server
You can avoid needless round trips to the Web Server using the following tips:
Implement Ajax UI whenever possible. The idea is to avoid full page refresh and only
update the portion of the page that needs to be changed. I think Scott's article gave
great information on how to implement Ajax Atlas and <atlas:updatepanel>
control.
Use Client Side Scripts. Client site validation can help reduce round trips that are
required to process user's request. In ASP.NET you can also use client side controls to
validate user input.
Use Page.ISPostBack property to ensure that you only perform page initialization
logic when a page is loaded the first time and not in response to client postbacks.
Collapse | Copy Code
If Not IsPostBack Then
LoadJScripts()
End If

In some situations performing postback event handling are unnecessary. You can use
client callbacks to read data from the server instead of performing a full round trip.
Click here for details.

4. Save viewstate only when necessary
ViewState

is used primarily by Server controls to retain state only on pages that post data
back to themselves. The information is passed to the client and read back in a hidden
variable. ViewState is an unnecessary overhead for pages that do not need it. As the
ViewState grows larger, it affects the performance of garbage collection. You can optimize
the way your application uses ViewState by following these tips:

Situation when you don't need ViewState
ViewState

is turned on in ASP.NET by default. You might not need ViewState because
your page is output-only or because you explicitly reload data for each request. You do not
need ViewState in the following situations:
Your page does not post back. If the page does not post information back to itself, if
the page is only used for output, and if the page does not rely on response processing,
you do not need ViewState.
You do not handle server control events. If your server controls do not handle events,
and if your server controls have no dynamic or data bound property values, or they are
set in code on every request, you do not need ViewState.
You repopulate controls with every page refresh. If you ignore old data, and if you
repopulate the server control each time the page is refreshed, you do not need
ViewState.

Disabling viewstate
There are several ways to disable ViewState at various levels:
To disable ViewState for a single control on a page, set the EnableViewState
property of the control to false.
To disable ViewState for a single page, set the EnableViewState attribute in the @
Page directive to false. i.e.
Collapse | Copy Code
<%@ Page EnableViewState="false" %>

To disable ViewState for a specific application, use the following element in the
Web.config file of the application:
Collapse | Copy Code
<pages enableViewState="false" />

To disable ViewState for all applications on a Web server, configure the <pages>
element in the Machine.config file as follows:
Collapse | Copy Code
<pages enableViewState="false" />

Determine the size of your ViewState
By enabling tracing for the page, you can monitor the ViewState size for each control. You
can use this information to determine the optimal size of the ViewState or if there are
controls in which the ViewState can be disabled.

5. Use session variables carefully
Avoid storing too much data in session variables, and make sure your session timeout is
reasonable. This can use a significant amount of server memory. Keep in mind that data
stored in session variables can hang out long after the user closes the browser. Too many
session variables can bring the server on its knees. Disable session state, if you are not using
session variables in the particular page or application.
To disable session state for a page, set the EnableSessionState attribute in the @
Page directive to false.i.e.
Collapse | Copy Code
<%@ Page EnableSessionState="false" %>

If a page requires access to session variables but will not create or modify them, set
the EnableSessionState attribute in the@ Page directive to ReadOnly. i.e.
Collapse | Copy Code
<%@ Page EnableSessionState="ReadOnly" %>
To disable session state for a specific application, use the following element in the
Web.config file of the application.
Collapse | Copy Code
<sessionState mode='Off'/>

To disable session state for all applications on your Web server, use the following
element in the Machine.config file:
Collapse | Copy Code
<sessionState mode='Off'/>

6. Use Server.Transfer
Use the Server.Transfer method to redirect between pages in the same application. Using
this method in a page, with Server.Transfer syntax, avoids unnecessary client-side
redirection. Consider Using Server.Transfer Instead of Response.Redirect. However,
you cannot always just replace Response.Redirect calls with Server.Transfer. If you
need authentication and authorization checks during redirection, use Response.Redirect
instead of Server.Transfer because the two mechanisms are not equivalent. When you use
Response.Redirect, ensure you use the overloaded method that accepts a Boolean second
parameter, and pass a value of false to ensure an internal exception is not raised. Also
note that you can only use Server.Transfer to transfer control to pages in the same
application. To transfer to pages in other applications, you must use Response.Redirect.

7. Use server controls when appropriate and avoid
creating deeply nested controls
The HTTP protocol is stateless; however, server controls provide a rich programming model
that manage state between page requests by using ViewState. However nothing comes for
free, server controls require a fixed amount of processing to establish the control and all of its
child controls. This makes server controls relatively expensive compared to HTML controls
or possibly static text. When you do not need rich interaction, replace server controls with an
inline representation of the user interface that you want to present. It is better to replace a
server control if:
You do not need to retain state across postbacks
The data that appears in the control is static or control displays read-only data
You do not need programmatic access to the control on the server-side
Alternatives to server controls include simple rendering, HTML elements, inline
Response.Write calls, and raw inline angle brackets (<% %>). It is essential to balance your
tradeoffs. Avoid over optimization if the overhead is acceptable and if your application is
within the limits of its performance objectives.
Deeply nested hierarchies of controls compound the cost of creating a server control and its
child controls. Deeply nested hierarchies create extra processing that could be avoided by
using a different design that uses inline controls, or by using a flatter hierarchy of server
controls. This is especially important when you use controls such as Repeater, DataList,
and DataGrid because they create additional child controls in the container.

8. Choose the data viewing control appropriate for your
solution
Depending on how you choose to display data in a Web Forms page, there are often
significant tradeoffs between convenience and performance. Always compare the pros and
cons of controls before you use them in your application. For example, you can choose any of
these three controls (DataGrid, DataList and Repeater) to display data, it's your job to find
out which control will provide you maximum benefit. The DataGrid control can be a quick
and easy way to display data, but it is frequently the most expensive in terms of performance.
Rendering the data yourself by generating the appropriate HTML may work in some simple
cases, but customization and browser targeting can quickly offset the extra work involved. A
Repeater Web server control is a compromise between convenience and performance. It is
efficient, customizable, and programmable.

9. Optimize code and exception handling
To optimize expensive loops, use For instead of ForEach in performance-critical code
paths. Also do not rely on exceptions in your code and write code that avoids exceptions.
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, do so. Do not catch the exception itself before you handle that
condition. Do not use exceptions to control logic. A database connection that fails to open is
an exception but a user who mistypes his password is simply a condition that needs to be
handled. Common scenarios include checking for null, assigning a value 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
code that tests for a condition. Both produce the same result.
Collapse | Copy Code
'Unnecessary use of exception
Try
value = 100 / number
Catch ex As Exception
value = 0
End Try
' Recommended code
If Not number = 0 Then
value = 100 / number
Else
value = 0
End If
Check for null values. If it is possible for an object to be null, check to make sure it is not
null, rather then throwing an exception. This commonly occurs when you retrieve items
from ViewState, session state, application state, or cache objects as well as query string and
form field variables. For example, do not use the following code to access session state
information.
Collapse | Copy Code
'Unnecessary use of exception
Try
value = HttpContext.Current.Session("Value").ToString
Catch ex As Exception
Response.Redirect("Main.aspx", False)
End Try
'Recommended code
If Not HttpContext.Current.Session("Value") Is Nothing Then
value = HttpContext.Current.Session("Value").ToString
Else
Response.Redirect("Main.aspx", False)
End If

10. Use a DataReader for fast and efficient data binding
Use a DataReader object if you do not need to cache data, if you are displaying read-only
data, and if you need to load data into a control as quickly as possible. The DataReader is
the optimum choice for retrieving read-only data in a forward-only manner. Loading the data
into a DataSet object and then binding the DataSet to the control moves the data twice.
This method also incurs the relatively significant expense of constructing a DataSet. In
addition, when you use the DataReader, you can use the specialized type-specific methods to
retrieve the data for better performance.

11. Use paging efficiently
Allowing users to request and retrieve more data than they can consume puts an unnecessary
strain on your application resources. This unnecessary strain causes increased CPU
utilization, increased memory consumption, and decreased response times. This is especially
true for clients that have a slow connection speed. From a usability standpoint, most users do
not want to see thousands of rows presented as a single unit. Implement a paging solution that
retrieves only the desired data from the database and reduces back-end work on the database.
You should optimize the number of rows returned by the Database Server to the middle-tier
web-server. For more information read this article to implement paging at the Database level.
If you are using SQL Server 2000, please also look at this article.

12. Explicitly Dispose or Close all the resources
To guarantee resources are cleaned up when an exception occurs, use a try/finally block.
Close the resources in the finally clause. Using a try/finally block ensures that
resources are disposed even if an exception occurs. Open your connection just before
needing it, and close it as soon as you're done with it. Your motto should always be "get in,
get/save data, get out." If you use different objects, make sure you call the Dispose method
of the object or the Close method if one is provided. Failing to call Close or Dispose
prolongs the life of the object in memory long after the client stops using it. This defers the
cleanup and can contribute to memory pressure. Database connection and files are examples
of shared resources that should be explicitly closed.
Collapse | Copy Code
Try
_con.Open()
Catch ex As Exception
Throw ex
Finally
If Not _con Is Nothing Then
_con.Close()
End If
End Try

13. Disable tracing and debugging
Before you deploy your application, disable tracing and debugging. Tracing and debugging
may cause performance issues. Tracing and debugging are not recommended while your
application is running in production. You can disable tracing and debugging in the
Machine.config and Web.config using the syntax below:
Collapse | Copy Code
<configuration>
<system.web>
<trace enabled="false" pageOutput="false" />
<compilation debug="false" />
</system.web>
</configuration>

14. Precompile pages and disable AutoEventWireup
By precompiled pages, users do not have to experience the batch compile of your ASP.NET
files; it will increase the performance that your users will experience.
In addition, setting the AutoEventWireup attribute to false in the Machine.config file
means that the page will not match method names to events and hook them up (for example,
Page_Load). If page developers want to use these events, they will need to override the
methods in the base class (for example, they will need to override Page.OnLoad for the page
load event instead of using a Page_Load method). If you disable AutoEventWireup, your
pages will get a slight performance boost by leaving the event wiring to the page author
instead of performing it automatically.

15. Use stored procedures and indexes
In most cases you can get an additional performance boost by using compiled stored
procedures instead of ad hoc queries.
Make sure you index your tables, and choose your indexes wisely. Try using Index Tuning
Wizard and have it report to you what it thinks the best candidates for indexes would be. You
don't have to follow all of its suggestions, but it may reveal things about your structure or
data that will help you choose more appropriate indexes.
In SQL Server Management Studio (SQL Server 2005), highlight your query. Now
from the Query menu, click Analyze Query in Database Engine Tuning Advisor.
You can do something similar in SQL Server 2000 to run the index tuning wizard? In
Query Analyzer, highlight your query. From the Query menu, click Index Tuning
Wizard.

References
Improving .NET Application Performance and Scalability (Retrieved 2006, February
12).

License
This article has no explicit license attached to it but may contain usage terms in the article
text or the download files themselves. If in doubt please contact the author via the discussion
board below.
A list of licenses authors might use can be found here

Más contenido relacionado

La actualidad más candente

Introduction To Asp.Net Ajax
Introduction To Asp.Net AjaxIntroduction To Asp.Net Ajax
Introduction To Asp.Net AjaxJeff Blankenburg
 
13 asp.net session19
13 asp.net session1913 asp.net session19
13 asp.net session19Vivek chan
 
Harish Understanding Aspnet
Harish Understanding AspnetHarish Understanding Aspnet
Harish Understanding Aspnetrsnarayanan
 
ASP.NET MVC Performance
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performancerudib
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questionsAkhil Mittal
 
Ajax control asp.net
Ajax control asp.netAjax control asp.net
Ajax control asp.netSireesh K
 
ASP.NET AJAX with Visual Studio 2008
ASP.NET AJAX with Visual Studio 2008ASP.NET AJAX with Visual Studio 2008
ASP.NET AJAX with Visual Studio 2008Caleb Jenkins
 
ajn11 BT appengine SDK updates
ajn11 BT appengine SDK updatesajn11 BT appengine SDK updates
ajn11 BT appengine SDK updatesSATOSHI TAGOMORI
 
SPSBE 2014 Content Enrichment in SharePoint Search
SPSBE 2014 Content Enrichment in SharePoint SearchSPSBE 2014 Content Enrichment in SharePoint Search
SPSBE 2014 Content Enrichment in SharePoint SearchSteven Van de Craen
 
Harish Aspnet Deployment
Harish Aspnet DeploymentHarish Aspnet Deployment
Harish Aspnet Deploymentrsnarayanan
 
ASP.NET Page Life Cycle
ASP.NET Page Life CycleASP.NET Page Life Cycle
ASP.NET Page Life CycleAbhishek Sur
 

La actualidad más candente (19)

Introduction To Asp.Net Ajax
Introduction To Asp.Net AjaxIntroduction To Asp.Net Ajax
Introduction To Asp.Net Ajax
 
13 asp.net session19
13 asp.net session1913 asp.net session19
13 asp.net session19
 
Harish Understanding Aspnet
Harish Understanding AspnetHarish Understanding Aspnet
Harish Understanding Aspnet
 
ASP.NET MVC Performance
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performance
 
Walther Aspnet4
Walther Aspnet4Walther Aspnet4
Walther Aspnet4
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questions
 
Ajax control asp.net
Ajax control asp.netAjax control asp.net
Ajax control asp.net
 
Walther Ajax4
Walther Ajax4Walther Ajax4
Walther Ajax4
 
ASP.NET AJAX with Visual Studio 2008
ASP.NET AJAX with Visual Studio 2008ASP.NET AJAX with Visual Studio 2008
ASP.NET AJAX with Visual Studio 2008
 
Ajax
AjaxAjax
Ajax
 
ajn11 BT appengine SDK updates
ajn11 BT appengine SDK updatesajn11 BT appengine SDK updates
ajn11 BT appengine SDK updates
 
SPSBE 2014 Content Enrichment in SharePoint Search
SPSBE 2014 Content Enrichment in SharePoint SearchSPSBE 2014 Content Enrichment in SharePoint Search
SPSBE 2014 Content Enrichment in SharePoint Search
 
QSpiders - Installation and Brief Dose of Load Runner
QSpiders - Installation and Brief Dose of Load RunnerQSpiders - Installation and Brief Dose of Load Runner
QSpiders - Installation and Brief Dose of Load Runner
 
Ajax part i
Ajax part iAjax part i
Ajax part i
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
Harish Aspnet Deployment
Harish Aspnet DeploymentHarish Aspnet Deployment
Harish Aspnet Deployment
 
AJAX in ASP.NET
AJAX in ASP.NETAJAX in ASP.NET
AJAX in ASP.NET
 
ASP.NET Page Life Cycle
ASP.NET Page Life CycleASP.NET Page Life Cycle
ASP.NET Page Life Cycle
 
2310 b 15
2310 b 152310 b 15
2310 b 15
 

Similar a High performance coding practices code project

How to optimize asp dot-net application
How to optimize asp dot-net applicationHow to optimize asp dot-net application
How to optimize asp dot-net applicationsonia merchant
 
How to optimize asp dot net application ?
How to optimize asp dot net application ?How to optimize asp dot net application ?
How to optimize asp dot net application ?sonia merchant
 
How To Optimize Asp.Net Application ?
How To Optimize Asp.Net Application ?How To Optimize Asp.Net Application ?
How To Optimize Asp.Net Application ?Pooja Gaikwad
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To MvcVolkan Uzun
 
New Features Of ASP.Net 4 0
New Features Of ASP.Net 4 0New Features Of ASP.Net 4 0
New Features Of ASP.Net 4 0Dima Maleev
 
Why use .net by naveen kumar veligeti
Why use .net by naveen kumar veligetiWhy use .net by naveen kumar veligeti
Why use .net by naveen kumar veligetiNaveen Kumar Veligeti
 
Ajax Testing Approach
Ajax Testing ApproachAjax Testing Approach
Ajax Testing ApproachHarshJ
 
Ajax Testing Approach
Ajax Testing ApproachAjax Testing Approach
Ajax Testing ApproachHarshaVJoshi
 
JOB PORTALProject SummaryTitle JOB-PORT.docx
JOB PORTALProject SummaryTitle    JOB-PORT.docxJOB PORTALProject SummaryTitle    JOB-PORT.docx
JOB PORTALProject SummaryTitle JOB-PORT.docxchristiandean12115
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083Divyam Pateriya
 
Which is better asp.net mvc vs asp.net
Which is better  asp.net mvc vs asp.netWhich is better  asp.net mvc vs asp.net
Which is better asp.net mvc vs asp.netConcetto Labs
 
IEEE KUET SPAC presentation
IEEE KUET SPAC  presentationIEEE KUET SPAC  presentation
IEEE KUET SPAC presentationahsanmm
 
Azure appservice
Azure appserviceAzure appservice
Azure appserviceRaju Kumar
 
Performace optimization (increase website speed)
Performace optimization (increase website speed)Performace optimization (increase website speed)
Performace optimization (increase website speed)clickramanm
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introductionTomi Juhola
 
ASP.NET 12 - State Management
ASP.NET 12 - State ManagementASP.NET 12 - State Management
ASP.NET 12 - State ManagementRandy Connolly
 

Similar a High performance coding practices code project (20)

How to optimize asp dot-net application
How to optimize asp dot-net applicationHow to optimize asp dot-net application
How to optimize asp dot-net application
 
How to optimize asp dot net application ?
How to optimize asp dot net application ?How to optimize asp dot net application ?
How to optimize asp dot net application ?
 
How To Optimize Asp.Net Application ?
How To Optimize Asp.Net Application ?How To Optimize Asp.Net Application ?
How To Optimize Asp.Net Application ?
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
 
Asp.net,mvc
Asp.net,mvcAsp.net,mvc
Asp.net,mvc
 
ASP.NET MVC Zero to Hero
ASP.NET MVC Zero to HeroASP.NET MVC Zero to Hero
ASP.NET MVC Zero to Hero
 
New Features Of ASP.Net 4 0
New Features Of ASP.Net 4 0New Features Of ASP.Net 4 0
New Features Of ASP.Net 4 0
 
Why use .net by naveen kumar veligeti
Why use .net by naveen kumar veligetiWhy use .net by naveen kumar veligeti
Why use .net by naveen kumar veligeti
 
Ajax Testing Approach
Ajax Testing ApproachAjax Testing Approach
Ajax Testing Approach
 
Ajax Testing Approach
Ajax Testing ApproachAjax Testing Approach
Ajax Testing Approach
 
JOB PORTALProject SummaryTitle JOB-PORT.docx
JOB PORTALProject SummaryTitle    JOB-PORT.docxJOB PORTALProject SummaryTitle    JOB-PORT.docx
JOB PORTALProject SummaryTitle JOB-PORT.docx
 
NET_Training.pptx
NET_Training.pptxNET_Training.pptx
NET_Training.pptx
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
 
Which is better asp.net mvc vs asp.net
Which is better  asp.net mvc vs asp.netWhich is better  asp.net mvc vs asp.net
Which is better asp.net mvc vs asp.net
 
IEEE KUET SPAC presentation
IEEE KUET SPAC  presentationIEEE KUET SPAC  presentation
IEEE KUET SPAC presentation
 
Top 5 React Performance Optimization Techniques in 2023
Top 5 React Performance Optimization Techniques in 2023Top 5 React Performance Optimization Techniques in 2023
Top 5 React Performance Optimization Techniques in 2023
 
Azure appservice
Azure appserviceAzure appservice
Azure appservice
 
Performace optimization (increase website speed)
Performace optimization (increase website speed)Performace optimization (increase website speed)
Performace optimization (increase website speed)
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
 
ASP.NET 12 - State Management
ASP.NET 12 - State ManagementASP.NET 12 - State Management
ASP.NET 12 - State Management
 

Último

Kalpataru Exquisite Wakad Pune E-Brochure.pdf
Kalpataru Exquisite Wakad Pune  E-Brochure.pdfKalpataru Exquisite Wakad Pune  E-Brochure.pdf
Kalpataru Exquisite Wakad Pune E-Brochure.pdfManishSaxena95
 
Top tourism places in Dubai - Inch & Brick Realty
Top tourism places in Dubai - Inch & Brick RealtyTop tourism places in Dubai - Inch & Brick Realty
Top tourism places in Dubai - Inch & Brick Realtypunitranainchbrick02
 
Best Interior Design Services in Haldwani
Best Interior Design Services in HaldwaniBest Interior Design Services in Haldwani
Best Interior Design Services in HaldwaniGeomatrix
 
Explore Dual Citizenship in Africa | Citizenship Benefits & Requirements
Explore Dual Citizenship in Africa | Citizenship Benefits & RequirementsExplore Dual Citizenship in Africa | Citizenship Benefits & Requirements
Explore Dual Citizenship in Africa | Citizenship Benefits & Requirementsmarketingkingdomofku
 
Bptp The Amaario Launch Luxury Project Sector 37D Gurgaon Dwarka Expressway...
Bptp The Amaario Launch  Luxury Project  Sector 37D Gurgaon Dwarka Expressway...Bptp The Amaario Launch  Luxury Project  Sector 37D Gurgaon Dwarka Expressway...
Bptp The Amaario Launch Luxury Project Sector 37D Gurgaon Dwarka Expressway...ApartmentWala1
 
Call girls in Shakti Nagar Delhi~8447779280°/=@/ Short 1500 Night 6000}ESCORT...
Call girls in Shakti Nagar Delhi~8447779280°/=@/ Short 1500 Night 6000}ESCORT...Call girls in Shakti Nagar Delhi~8447779280°/=@/ Short 1500 Night 6000}ESCORT...
Call girls in Shakti Nagar Delhi~8447779280°/=@/ Short 1500 Night 6000}ESCORT...asmaqueen5
 
MEQ Mainstreet Equity Corp Q2 2024 Investor Presentation
MEQ Mainstreet Equity Corp Q2 2024 Investor PresentationMEQ Mainstreet Equity Corp Q2 2024 Investor Presentation
MEQ Mainstreet Equity Corp Q2 2024 Investor PresentationMEQ - Mainstreet Equity Corp.
 
Call girls In Rana Pratap Bagh {Delhi ↫8447779280↬Escort Service (Delhi)
Call girls In Rana Pratap Bagh {Delhi ↫8447779280↬Escort Service (Delhi)Call girls In Rana Pratap Bagh {Delhi ↫8447779280↬Escort Service (Delhi)
Call girls In Rana Pratap Bagh {Delhi ↫8447779280↬Escort Service (Delhi)asmaqueen5
 
Nyati Elite NIBM Road Pune E Brochure.pdf
Nyati Elite NIBM Road Pune E Brochure.pdfNyati Elite NIBM Road Pune E Brochure.pdf
Nyati Elite NIBM Road Pune E Brochure.pdfabbu831446
 
Kohinoor Teiko Hinjewadi Phase 2 Pune E-Brochure.pdf
Kohinoor Teiko Hinjewadi Phase 2 Pune  E-Brochure.pdfKohinoor Teiko Hinjewadi Phase 2 Pune  E-Brochure.pdf
Kohinoor Teiko Hinjewadi Phase 2 Pune E-Brochure.pdfManishSaxena95
 
Housing Price Regulation Thesis Defense by Slidesgo.pptx
Housing Price Regulation Thesis Defense by Slidesgo.pptxHousing Price Regulation Thesis Defense by Slidesgo.pptx
Housing Price Regulation Thesis Defense by Slidesgo.pptxcosmo-soil
 
BPTP THE AMAARIO For The Royals Of Tomorrow in Sector 37D Gurgaon Dwarka Expr...
BPTP THE AMAARIO For The Royals Of Tomorrow in Sector 37D Gurgaon Dwarka Expr...BPTP THE AMAARIO For The Royals Of Tomorrow in Sector 37D Gurgaon Dwarka Expr...
BPTP THE AMAARIO For The Royals Of Tomorrow in Sector 37D Gurgaon Dwarka Expr...ApartmentWala1
 
Jaipur Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Jaipur Escorts 🥰 8617370543 Call Girls Offer VIP Hot GirlsJaipur Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Jaipur Escorts 🥰 8617370543 Call Girls Offer VIP Hot GirlsDeepika Singh
 
Bridge & Elliot Ladner Floor Plans May 2024.pdf
Bridge & Elliot Ladner Floor Plans May 2024.pdfBridge & Elliot Ladner Floor Plans May 2024.pdf
Bridge & Elliot Ladner Floor Plans May 2024.pdfVickyAulakh1
 
Low Density Living New Project in BPTP THE AMAARIO Sector 37D Gurgaon Haryana...
Low Density Living New Project in BPTP THE AMAARIO Sector 37D Gurgaon Haryana...Low Density Living New Project in BPTP THE AMAARIO Sector 37D Gurgaon Haryana...
Low Density Living New Project in BPTP THE AMAARIO Sector 37D Gurgaon Haryana...ApartmentWala1
 
SVN Live 5.6.24 Weekly Property Broadcast
SVN Live 5.6.24 Weekly Property BroadcastSVN Live 5.6.24 Weekly Property Broadcast
SVN Live 5.6.24 Weekly Property BroadcastSVN International Corp.
 
Call Girls In Sarai Rohilla ☎️8447779280{Sarai Rohilla Escort Service In Delh...
Call Girls In Sarai Rohilla ☎️8447779280{Sarai Rohilla Escort Service In Delh...Call Girls In Sarai Rohilla ☎️8447779280{Sarai Rohilla Escort Service In Delh...
Call Girls In Sarai Rohilla ☎️8447779280{Sarai Rohilla Escort Service In Delh...asmaqueen5
 
Parksville 96 Surrey Floor Plans May 2024
Parksville 96 Surrey Floor Plans May 2024Parksville 96 Surrey Floor Plans May 2024
Parksville 96 Surrey Floor Plans May 2024VickyAulakh1
 
Low Rate ✨➥9711108085▻✨Call Girls In Majnu Ka Tilla (Mt) (Delhi)
Low Rate ✨➥9711108085▻✨Call Girls In Majnu Ka Tilla (Mt) (Delhi)Low Rate ✨➥9711108085▻✨Call Girls In Majnu Ka Tilla (Mt) (Delhi)
Low Rate ✨➥9711108085▻✨Call Girls In Majnu Ka Tilla (Mt) (Delhi)delhi24hrs1
 
Yashwin Enchante Uppar Kharadi Pune E-Brochue.pdf
Yashwin Enchante Uppar Kharadi Pune  E-Brochue.pdfYashwin Enchante Uppar Kharadi Pune  E-Brochue.pdf
Yashwin Enchante Uppar Kharadi Pune E-Brochue.pdfManishSaxena95
 

Último (20)

Kalpataru Exquisite Wakad Pune E-Brochure.pdf
Kalpataru Exquisite Wakad Pune  E-Brochure.pdfKalpataru Exquisite Wakad Pune  E-Brochure.pdf
Kalpataru Exquisite Wakad Pune E-Brochure.pdf
 
Top tourism places in Dubai - Inch & Brick Realty
Top tourism places in Dubai - Inch & Brick RealtyTop tourism places in Dubai - Inch & Brick Realty
Top tourism places in Dubai - Inch & Brick Realty
 
Best Interior Design Services in Haldwani
Best Interior Design Services in HaldwaniBest Interior Design Services in Haldwani
Best Interior Design Services in Haldwani
 
Explore Dual Citizenship in Africa | Citizenship Benefits & Requirements
Explore Dual Citizenship in Africa | Citizenship Benefits & RequirementsExplore Dual Citizenship in Africa | Citizenship Benefits & Requirements
Explore Dual Citizenship in Africa | Citizenship Benefits & Requirements
 
Bptp The Amaario Launch Luxury Project Sector 37D Gurgaon Dwarka Expressway...
Bptp The Amaario Launch  Luxury Project  Sector 37D Gurgaon Dwarka Expressway...Bptp The Amaario Launch  Luxury Project  Sector 37D Gurgaon Dwarka Expressway...
Bptp The Amaario Launch Luxury Project Sector 37D Gurgaon Dwarka Expressway...
 
Call girls in Shakti Nagar Delhi~8447779280°/=@/ Short 1500 Night 6000}ESCORT...
Call girls in Shakti Nagar Delhi~8447779280°/=@/ Short 1500 Night 6000}ESCORT...Call girls in Shakti Nagar Delhi~8447779280°/=@/ Short 1500 Night 6000}ESCORT...
Call girls in Shakti Nagar Delhi~8447779280°/=@/ Short 1500 Night 6000}ESCORT...
 
MEQ Mainstreet Equity Corp Q2 2024 Investor Presentation
MEQ Mainstreet Equity Corp Q2 2024 Investor PresentationMEQ Mainstreet Equity Corp Q2 2024 Investor Presentation
MEQ Mainstreet Equity Corp Q2 2024 Investor Presentation
 
Call girls In Rana Pratap Bagh {Delhi ↫8447779280↬Escort Service (Delhi)
Call girls In Rana Pratap Bagh {Delhi ↫8447779280↬Escort Service (Delhi)Call girls In Rana Pratap Bagh {Delhi ↫8447779280↬Escort Service (Delhi)
Call girls In Rana Pratap Bagh {Delhi ↫8447779280↬Escort Service (Delhi)
 
Nyati Elite NIBM Road Pune E Brochure.pdf
Nyati Elite NIBM Road Pune E Brochure.pdfNyati Elite NIBM Road Pune E Brochure.pdf
Nyati Elite NIBM Road Pune E Brochure.pdf
 
Kohinoor Teiko Hinjewadi Phase 2 Pune E-Brochure.pdf
Kohinoor Teiko Hinjewadi Phase 2 Pune  E-Brochure.pdfKohinoor Teiko Hinjewadi Phase 2 Pune  E-Brochure.pdf
Kohinoor Teiko Hinjewadi Phase 2 Pune E-Brochure.pdf
 
Housing Price Regulation Thesis Defense by Slidesgo.pptx
Housing Price Regulation Thesis Defense by Slidesgo.pptxHousing Price Regulation Thesis Defense by Slidesgo.pptx
Housing Price Regulation Thesis Defense by Slidesgo.pptx
 
BPTP THE AMAARIO For The Royals Of Tomorrow in Sector 37D Gurgaon Dwarka Expr...
BPTP THE AMAARIO For The Royals Of Tomorrow in Sector 37D Gurgaon Dwarka Expr...BPTP THE AMAARIO For The Royals Of Tomorrow in Sector 37D Gurgaon Dwarka Expr...
BPTP THE AMAARIO For The Royals Of Tomorrow in Sector 37D Gurgaon Dwarka Expr...
 
Jaipur Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Jaipur Escorts 🥰 8617370543 Call Girls Offer VIP Hot GirlsJaipur Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Jaipur Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
 
Bridge & Elliot Ladner Floor Plans May 2024.pdf
Bridge & Elliot Ladner Floor Plans May 2024.pdfBridge & Elliot Ladner Floor Plans May 2024.pdf
Bridge & Elliot Ladner Floor Plans May 2024.pdf
 
Low Density Living New Project in BPTP THE AMAARIO Sector 37D Gurgaon Haryana...
Low Density Living New Project in BPTP THE AMAARIO Sector 37D Gurgaon Haryana...Low Density Living New Project in BPTP THE AMAARIO Sector 37D Gurgaon Haryana...
Low Density Living New Project in BPTP THE AMAARIO Sector 37D Gurgaon Haryana...
 
SVN Live 5.6.24 Weekly Property Broadcast
SVN Live 5.6.24 Weekly Property BroadcastSVN Live 5.6.24 Weekly Property Broadcast
SVN Live 5.6.24 Weekly Property Broadcast
 
Call Girls In Sarai Rohilla ☎️8447779280{Sarai Rohilla Escort Service In Delh...
Call Girls In Sarai Rohilla ☎️8447779280{Sarai Rohilla Escort Service In Delh...Call Girls In Sarai Rohilla ☎️8447779280{Sarai Rohilla Escort Service In Delh...
Call Girls In Sarai Rohilla ☎️8447779280{Sarai Rohilla Escort Service In Delh...
 
Parksville 96 Surrey Floor Plans May 2024
Parksville 96 Surrey Floor Plans May 2024Parksville 96 Surrey Floor Plans May 2024
Parksville 96 Surrey Floor Plans May 2024
 
Low Rate ✨➥9711108085▻✨Call Girls In Majnu Ka Tilla (Mt) (Delhi)
Low Rate ✨➥9711108085▻✨Call Girls In Majnu Ka Tilla (Mt) (Delhi)Low Rate ✨➥9711108085▻✨Call Girls In Majnu Ka Tilla (Mt) (Delhi)
Low Rate ✨➥9711108085▻✨Call Girls In Majnu Ka Tilla (Mt) (Delhi)
 
Yashwin Enchante Uppar Kharadi Pune E-Brochue.pdf
Yashwin Enchante Uppar Kharadi Pune  E-Brochue.pdfYashwin Enchante Uppar Kharadi Pune  E-Brochue.pdf
Yashwin Enchante Uppar Kharadi Pune E-Brochue.pdf
 

High performance coding practices code project

  • 1. ASP.NET Best Practices for High Performance Applications By Ali Khan (OKC), 21 Mar 2006 4.65 (165 votes) Introduction ASP.NET is much more powerful than classic ASP, however it is important to understand how to use that power to build highly efficient, reliable and robust applications. In this article, I tried to highlight the key tips you can use to maximize the performance of your ASP.NET pages. The list can be much longer, I am only emphasizing the most important ones. 1. Plan and research before you develop Research and investigate how .NET can really benefit you. .NET offers a variety of solutions on each level of application design and development. It is imperative that you understand your situation and pros and cons of each approach supported by this rich development environment. Visual Studio is a comprehensive development package and offers many options to implement the same logic. It is really important that you examine each option and find the best optimal solution suited for the task at hand. Use layering to logically partition your application logic into presentation, business, and data access layers. It will not only help you create maintainable code, but also permits you to monitor and optimize the performance of each layer separately. A clear logical separation also offers more choices for scaling your application. Try to reduce the amount of code in your code-behind files to improve maintenance and scalability. 2. String concatenation If not handled properly, String Concatenation can really decrease the performance of your application. You can concatenate strings in two ways. First, by using string and adding the new string to an existing string. However, this operation is really expensive (especially if you are concatenating the string within a loop). When you add a string to an existing string, the Framework copies both the existing and new data to the memory, deletes the existing string, and reads data in a new string. This operation can be very time consuming and costly in lengthy string concatenation operations. The second and better way to concatenate strings is using the StringBuilder Class. Below is an example of both approaches. If you are considering doing any type of String Concatenation, please do yourself a favor and test both routines separately. You may be surprised at the results. Collapse | Copy Code
  • 2. 'Concatenation using String Class Response.Write("<b>String Class</b>") Dim str As String = "" Dim startTime As DateTime = DateTime.Now Response.Write(("<br>Start time:" + startTime.ToString())) Dim i As Integer For i = 0 To 99999 str += i.ToString() Next i Dim EndTime As DateTime = DateTime.Now Response.Write(("<br>End time:" + EndTime.ToString())) Response.Write(("<br># of time Concatenated: " + i.ToString)) Results: Took 4 minutes and 23 Seconds to to complete 100,000 Concatenations. String o o o Class Start time: 2/15/2006 10:21:24 AM End time: 2/15/2006 10:25:47 AM # of time Concatenated: 100000 Collapse | Copy Code 'Concatenation using StringBuilder Response.Write("<b>StringBuilder Class</b>") Dim strbuilder As New StringBuilder() Dim startTime As DateTime = DateTime.Now Response.Write(("<br>Start time:" + startTime.ToString())) Dim i As Integer For i = 0 To 99999 strbuilder.Append(i.ToString()) Next i Dim EndTime As DateTime = DateTime.Now Response.Write(("<br>Stop time:" + EndTime.ToString())) Response.Write(("<br># of time Concatenated: " + i.ToString)) Results: Took less than a Second to complete 100,000 Concatenations. StringBuilder o o o Class Start time: 2/15/2006 10:31:22 AM Stop time:2/15/2006 10:31:22 AM # of time Concatenated: 100000 This is one of the many situations in which ASP.NET provides extremely high performance benefits over classic ASP. 3. Avoid round trips to the server You can avoid needless round trips to the Web Server using the following tips: Implement Ajax UI whenever possible. The idea is to avoid full page refresh and only update the portion of the page that needs to be changed. I think Scott's article gave
  • 3. great information on how to implement Ajax Atlas and <atlas:updatepanel> control. Use Client Side Scripts. Client site validation can help reduce round trips that are required to process user's request. In ASP.NET you can also use client side controls to validate user input. Use Page.ISPostBack property to ensure that you only perform page initialization logic when a page is loaded the first time and not in response to client postbacks. Collapse | Copy Code If Not IsPostBack Then LoadJScripts() End If In some situations performing postback event handling are unnecessary. You can use client callbacks to read data from the server instead of performing a full round trip. Click here for details. 4. Save viewstate only when necessary ViewState is used primarily by Server controls to retain state only on pages that post data back to themselves. The information is passed to the client and read back in a hidden variable. ViewState is an unnecessary overhead for pages that do not need it. As the ViewState grows larger, it affects the performance of garbage collection. You can optimize the way your application uses ViewState by following these tips: Situation when you don't need ViewState ViewState is turned on in ASP.NET by default. You might not need ViewState because your page is output-only or because you explicitly reload data for each request. You do not need ViewState in the following situations: Your page does not post back. If the page does not post information back to itself, if the page is only used for output, and if the page does not rely on response processing, you do not need ViewState. You do not handle server control events. If your server controls do not handle events, and if your server controls have no dynamic or data bound property values, or they are set in code on every request, you do not need ViewState. You repopulate controls with every page refresh. If you ignore old data, and if you repopulate the server control each time the page is refreshed, you do not need ViewState. Disabling viewstate There are several ways to disable ViewState at various levels: To disable ViewState for a single control on a page, set the EnableViewState property of the control to false.
  • 4. To disable ViewState for a single page, set the EnableViewState attribute in the @ Page directive to false. i.e. Collapse | Copy Code <%@ Page EnableViewState="false" %> To disable ViewState for a specific application, use the following element in the Web.config file of the application: Collapse | Copy Code <pages enableViewState="false" /> To disable ViewState for all applications on a Web server, configure the <pages> element in the Machine.config file as follows: Collapse | Copy Code <pages enableViewState="false" /> Determine the size of your ViewState By enabling tracing for the page, you can monitor the ViewState size for each control. You can use this information to determine the optimal size of the ViewState or if there are controls in which the ViewState can be disabled. 5. Use session variables carefully Avoid storing too much data in session variables, and make sure your session timeout is reasonable. This can use a significant amount of server memory. Keep in mind that data stored in session variables can hang out long after the user closes the browser. Too many session variables can bring the server on its knees. Disable session state, if you are not using session variables in the particular page or application. To disable session state for a page, set the EnableSessionState attribute in the @ Page directive to false.i.e. Collapse | Copy Code <%@ Page EnableSessionState="false" %> If a page requires access to session variables but will not create or modify them, set the EnableSessionState attribute in the@ Page directive to ReadOnly. i.e. Collapse | Copy Code <%@ Page EnableSessionState="ReadOnly" %>
  • 5. To disable session state for a specific application, use the following element in the Web.config file of the application. Collapse | Copy Code <sessionState mode='Off'/> To disable session state for all applications on your Web server, use the following element in the Machine.config file: Collapse | Copy Code <sessionState mode='Off'/> 6. Use Server.Transfer Use the Server.Transfer method to redirect between pages in the same application. Using this method in a page, with Server.Transfer syntax, avoids unnecessary client-side redirection. Consider Using Server.Transfer Instead of Response.Redirect. However, you cannot always just replace Response.Redirect calls with Server.Transfer. If you need authentication and authorization checks during redirection, use Response.Redirect instead of Server.Transfer because the two mechanisms are not equivalent. When you use Response.Redirect, ensure you use the overloaded method that accepts a Boolean second parameter, and pass a value of false to ensure an internal exception is not raised. Also note that you can only use Server.Transfer to transfer control to pages in the same application. To transfer to pages in other applications, you must use Response.Redirect. 7. Use server controls when appropriate and avoid creating deeply nested controls The HTTP protocol is stateless; however, server controls provide a rich programming model that manage state between page requests by using ViewState. However nothing comes for free, server controls require a fixed amount of processing to establish the control and all of its child controls. This makes server controls relatively expensive compared to HTML controls or possibly static text. When you do not need rich interaction, replace server controls with an inline representation of the user interface that you want to present. It is better to replace a server control if: You do not need to retain state across postbacks The data that appears in the control is static or control displays read-only data You do not need programmatic access to the control on the server-side Alternatives to server controls include simple rendering, HTML elements, inline Response.Write calls, and raw inline angle brackets (<% %>). It is essential to balance your tradeoffs. Avoid over optimization if the overhead is acceptable and if your application is within the limits of its performance objectives.
  • 6. Deeply nested hierarchies of controls compound the cost of creating a server control and its child controls. Deeply nested hierarchies create extra processing that could be avoided by using a different design that uses inline controls, or by using a flatter hierarchy of server controls. This is especially important when you use controls such as Repeater, DataList, and DataGrid because they create additional child controls in the container. 8. Choose the data viewing control appropriate for your solution Depending on how you choose to display data in a Web Forms page, there are often significant tradeoffs between convenience and performance. Always compare the pros and cons of controls before you use them in your application. For example, you can choose any of these three controls (DataGrid, DataList and Repeater) to display data, it's your job to find out which control will provide you maximum benefit. The DataGrid control can be a quick and easy way to display data, but it is frequently the most expensive in terms of performance. Rendering the data yourself by generating the appropriate HTML may work in some simple cases, but customization and browser targeting can quickly offset the extra work involved. A Repeater Web server control is a compromise between convenience and performance. It is efficient, customizable, and programmable. 9. Optimize code and exception handling To optimize expensive loops, use For instead of ForEach in performance-critical code paths. Also do not rely on exceptions in your code and write code that avoids exceptions. 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, do so. Do not catch the exception itself before you handle that condition. Do not use exceptions to control logic. A database connection that fails to open is an exception but a user who mistypes his password is simply a condition that needs to be handled. Common scenarios include checking for null, assigning a value 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 code that tests for a condition. Both produce the same result. Collapse | Copy Code 'Unnecessary use of exception Try value = 100 / number Catch ex As Exception value = 0 End Try ' Recommended code If Not number = 0 Then value = 100 / number Else value = 0 End If
  • 7. Check for null values. If it is possible for an object to be null, check to make sure it is not null, rather then throwing an exception. This commonly occurs when you retrieve items from ViewState, session state, application state, or cache objects as well as query string and form field variables. For example, do not use the following code to access session state information. Collapse | Copy Code 'Unnecessary use of exception Try value = HttpContext.Current.Session("Value").ToString Catch ex As Exception Response.Redirect("Main.aspx", False) End Try 'Recommended code If Not HttpContext.Current.Session("Value") Is Nothing Then value = HttpContext.Current.Session("Value").ToString Else Response.Redirect("Main.aspx", False) End If 10. Use a DataReader for fast and efficient data binding Use a DataReader object if you do not need to cache data, if you are displaying read-only data, and if you need to load data into a control as quickly as possible. The DataReader is the optimum choice for retrieving read-only data in a forward-only manner. Loading the data into a DataSet object and then binding the DataSet to the control moves the data twice. This method also incurs the relatively significant expense of constructing a DataSet. In addition, when you use the DataReader, you can use the specialized type-specific methods to retrieve the data for better performance. 11. Use paging efficiently Allowing users to request and retrieve more data than they can consume puts an unnecessary strain on your application resources. This unnecessary strain causes increased CPU utilization, increased memory consumption, and decreased response times. This is especially true for clients that have a slow connection speed. From a usability standpoint, most users do not want to see thousands of rows presented as a single unit. Implement a paging solution that retrieves only the desired data from the database and reduces back-end work on the database. You should optimize the number of rows returned by the Database Server to the middle-tier web-server. For more information read this article to implement paging at the Database level. If you are using SQL Server 2000, please also look at this article. 12. Explicitly Dispose or Close all the resources To guarantee resources are cleaned up when an exception occurs, use a try/finally block. Close the resources in the finally clause. Using a try/finally block ensures that resources are disposed even if an exception occurs. Open your connection just before needing it, and close it as soon as you're done with it. Your motto should always be "get in, get/save data, get out." If you use different objects, make sure you call the Dispose method
  • 8. of the object or the Close method if one is provided. Failing to call Close or Dispose prolongs the life of the object in memory long after the client stops using it. This defers the cleanup and can contribute to memory pressure. Database connection and files are examples of shared resources that should be explicitly closed. Collapse | Copy Code Try _con.Open() Catch ex As Exception Throw ex Finally If Not _con Is Nothing Then _con.Close() End If End Try 13. Disable tracing and debugging Before you deploy your application, disable tracing and debugging. Tracing and debugging may cause performance issues. Tracing and debugging are not recommended while your application is running in production. You can disable tracing and debugging in the Machine.config and Web.config using the syntax below: Collapse | Copy Code <configuration> <system.web> <trace enabled="false" pageOutput="false" /> <compilation debug="false" /> </system.web> </configuration> 14. Precompile pages and disable AutoEventWireup By precompiled pages, users do not have to experience the batch compile of your ASP.NET files; it will increase the performance that your users will experience. In addition, setting the AutoEventWireup attribute to false in the Machine.config file means that the page will not match method names to events and hook them up (for example, Page_Load). If page developers want to use these events, they will need to override the methods in the base class (for example, they will need to override Page.OnLoad for the page load event instead of using a Page_Load method). If you disable AutoEventWireup, your pages will get a slight performance boost by leaving the event wiring to the page author instead of performing it automatically. 15. Use stored procedures and indexes In most cases you can get an additional performance boost by using compiled stored procedures instead of ad hoc queries. Make sure you index your tables, and choose your indexes wisely. Try using Index Tuning Wizard and have it report to you what it thinks the best candidates for indexes would be. You
  • 9. don't have to follow all of its suggestions, but it may reveal things about your structure or data that will help you choose more appropriate indexes. In SQL Server Management Studio (SQL Server 2005), highlight your query. Now from the Query menu, click Analyze Query in Database Engine Tuning Advisor. You can do something similar in SQL Server 2000 to run the index tuning wizard? In Query Analyzer, highlight your query. From the Query menu, click Index Tuning Wizard. References Improving .NET Application Performance and Scalability (Retrieved 2006, February 12). License This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here