. NET program Optimization

Source: Internet
Author: User
Tags add numbers html form

First, the database operation

1. Close database connection immediately after use

Accessing a database resource requires creating a connection, opening a connection, and closing the connection several operations. These processes need to exchange information with the database multiple times to pass the authentication, which consumes the server

Source. Connection pooling (Connection pool) is provided in ASP . NET to improve the performance impact of opening and shutting down the database. The system places the user's database connection in the connection pool, takes out when needed, reclaims the connection when it closes, and waits for the next connection request.


The size of the connection pool is limited, and if you still need to create a connection when the connection pool reaches the maximum, you will inevitably have a significant impact on performance. Therefore, after establishing a database connection only when the actual need to open the connection, the use is closed immediately, so as to minimize the database connection open time, to avoid the situation beyond the connection limit.

Use (recommended)
using (SqlConnection conn=new SqlConnection (CONNSTR))
{}//does not have to show off

Or
Try{conn. Open ();}
catch{}
Finally{conn. Close ();}


2. Use stored procedures as much as possible and refine query statements

A stored procedure is a set of precompiled SQL statements stored on the server, similar to a batch file in a DOS system. Stored procedures have immediate access to the database and information processing is extremely rapid. You can use stored procedures to avoid multiple compilations of commands, and after execution, their execution plans reside in the cache, and you need to call the binary code in the cache directly later. In all of the data access methods provided by the. NET Framework, SQL Server -based data access is the recommended choice for building high-performance, scalable WEB applications. When you use a managed SQL Server provider, you gain additional performance gains by using compiled stored procedures instead of special queries.

In addition, stored procedures run on the server side, independent of the ASP. NET program, easy to modify, most importantly, it can reduce the database operation statements in the network transmission.

Refine query statements

Asp. NET ADO connections consume a considerable amount of resources, the longer the SQL statement runs, the longer it takes to take up system resources. Therefore, use optimized SQL statements as much as possible to reduce execution time. For example, do not include subqueries in query statements, try to return only useful data, fields, make full use of indexes, and so on.


3, read-only data access with SqlDataReader, do not use a dataset

The SqlDataReader class provides a way to read a forward-only stream of data retrieved from a SQL Server database. The SqlDataReader class provides higher performance than the DataSet class if you are allowed to use it when you create an ASP. This is the case because SqlDataReader uses SQL Server's native network data transfer format to read data directly from the database connection. In addition, the SqlDataReader class implements the IEnumerable interface, which also allows you to bind data to server controls. The dataset is a powerful, offline-enabled database with relatively high performance overhead.

Sqldataread Advantage: Read data very quickly. If you do not need to do a lot of processing of the returned data, it is recommended to use SqlDataReader, which has a much better performance than Datset. Disadvantage: Close the connection to the database until the data is read out.


The dataset reads the data and slows it down in memory. Cons: High memory usage. If you need to do a lot of processing of the returned data with a dataset, you can reduce the connection operation to the database. Pros: You can close the connection to the database with just one connection.

In general, read large amounts of data, do not do a lot of processing to return data with SqlDataReader. It is appropriate to use Datset for large amounts of returned data. The selection of SqlDataReader and datasets depends on the implementation of the program functions.


4, the data binding DataBinder

The general binding method <%# DataBinder.Eval (Container.DataItem, "field name")%>

Binding with DataBinder.Eval does not have to care about the data source (read or dataset). Do not care about the type of data eval converts the data object to a string. A lot of work was done at the bottom of the binding, using reflective performance. This is because it is easy to use, but it affects data performance.

See <%# DataBinder.Eval (Container.DataItem, "field name")%>. When binding to a DataSet, DataItem is actually a datarowview (if it is a data reader (Dataread) it is a idatarecord. Therefore, the direct conversion to DataRowView will bring a significant improvement in performance.

<%# CType (Container.dataitem,datarowview). Row ("field name")%>

Binding to data is recommended using <%# CType (Container.dataitem,datarowview). Row ("field name")%>. Note Two aspects when using:
1. You need to add <%@ Import namespace= "System.Data"%> on the page.
2. Note the case of the field name (pay special attention). If inconsistent with the query, in some cases results in slower than <%# DataBinder.Eval (Container.DataItem, "field name")%>. If you want to increase speed further, you can use <%# CType (Container.dataitem,datarowview). Row (0)%> method. But its readability is not high.

The above is the vb.net of the wording. In C #: <%# ((DataRowView) Container.DataItem) ["Field name"]%>

5. Return multiple result sets

Returns multiple result sets, whether SqlDataReader or Datset, and then uses Rd. NextResult () or DS. Tables[i] To process the data separately, reducing the number of times the database is repeatedly connected. At the same time try to use more efficient SQL instead of the subsequent complex dataset two processing.

Second, the page optimization


1. Do not use unnecessary server controls (SQL Server control)

In ASP. NET, a large number of server-side controls facilitates program development, but can also result in a loss of performance, as users produce a round-trip to the server side each time the server-side control is operated. Therefore, it is not necessary to use server Control sparingly. There are many other scenarios in which rendering or data binding is more efficient than using server controls, even when using server control templates. However, if you want to manipulate the properties of a server control programmatically, handle server control events, or save with view state, it is appropriate to use server controls.

So, try to choose the HTML control. The functionality that can be implemented on the client is implemented on the client side (mastering JavaScript), reducing the pressure on the server.


2, do not use unnecessary ViewState

By default, ASP. NET has ViewState (view state) enabled for all server control. But ViewState needs to save some information on the client, which can result in a performance drain. When you must use server control, you can consider prohibiting viewstate.
Save the server control view state only when necessary. Automatic view state Management is a feature of server controls that enable server controls to repopulate their property values on round trips (you do not need to write any code). However, because the view state of the server control is round-tripping to the server in a hidden form field, the feature does have a performance impact. You should be aware of the circumstances under which view state can be helpful, and in which cases it affects the performance of the page. For example, if you bind a server control to data on each round trip, the saved view state is replaced with the new value obtained from the data-binding operation. In this case, disabling view state can save processing time.

By default, view state is enabled for all server controls. To disable view state, set the control's EnableViewState property to False, as shown in the following example of the DataGrid server control.

<asp:datagrid enableviewstate= "false" runat= "Server"/>
You can also disable view state for the entire page by using the @ Page directive. This is useful when you are not sending back to the server from the page: <%@ page enableviewstate= "false"%>

Note The EnableViewState property is also supported in the @ Control directive, which allows you to control whether view state is enabled for a user control.
To analyze the number of view states used by server controls on a page, enable tracing for the page by including the Trace= "true" property in the @ Page directive and view the Viewstate column of the Control Hierarchy table.

3. Avoid unnecessary round trips to the server

While it is likely that you want to use as much of the time and code-saving features of the Web Forms page framework as possible, it is not appropriate to use the ASP. NET server control and postback event handling in some cases.

Typically, you only need to initiate a round trip to the server when you retrieve or store data. Most data operations can be performed on clients between these round trips. For example, validating user input from an HTML form can often be done on the client before the data is submitted to the server. In general, if you do not need to pass information to the server to store it in a database, you should not write code that results in a round-trip process.

If you are developing custom server controls, consider having them support ECMAScript. The browser renders the client code. By using server controls in this way, you can significantly reduce the number of times that information is sent to the WEB server unnecessarily.

Use Page.IsPostBack to avoid unnecessary processing of round trips

If you write code that handles postback processing for a server control, you may sometimes need to execute additional code when the page is first requested, rather than when the user sends the HTML form that is contained in the page. Use the Page.IsPostBack property to conditionally execute code, depending on whether the page was generated in response to a server control event. For example, the following code shows how to create a database connection and a command that binds data to a DataGrid server control the first time the page is requested.

void Page_Load (Object sender, EventArgs e)
{
if (! Page.IsPostBack)
{}
}

Because the Page_Load event is executed on each request, the code above checks to see if the IsPostBack property is set to False. If it is, execute the code. If the property is set to True, the code is not executed.

Note If you do not run this check, the behavior of the postback page will not change. The code for the Page_Load event executes before the server control event is executed, but only the results of the server control event may be rendered on the output page. If you do not run the check, processing will still be performed for the Page_Load event and any server control events on the page.


4, disable it when not using session state, and use the session as little as possible in program development

Not all applications or pages require session state for a specific user, and you should disable session state for any application or page that does not require session state.

To disable session state for a page, set the EnableSessionState property in the @ Page directive to false. Example: <%@ page enablesessionstate= "false"%>

Note If the page requires access to session variables but does not intend to create or modify them, the EnableSessionState property in the @ Page directive is set to ReadOnly.


To disable session state for an application, set the Mode property to off in the sessionstate configuration section of the application Web. config file. Example: <sessionstate mode= "Off"/>


5. Reasonable use of the DataGrid (for GridView in asp.net2.0) control

The DataGrid control has the most powerful data display capabilities, as well as the ability to modify, delete, add, and page out data. If you simply display the data, the DataGrid is not the best choice. The paging function of the DataGrid control, how the data is stored (stored in ViewState), and so on, while making it easy for program developers to use, the resulting performance overhead is not negligible.

The DataList control is much less powerful than the DataGrid. But the customization is much stronger. The unique multi-line data display is more convenient. The function that the DataGrid can achieve, it basically can realize.

Repeater controls have the least functionality, but are highly customizable. Because of the reduced functionality, the performance of the server is minimized.

Therefore, when you simply display a list of data, selecting the Repeater or DataList control also achieves the same purpose and reduces the overhead of performance.

Suggested selection order: Repeater then datalist the last DataGrid (GridView)

6. Paging the data

Asp. NET is a very useful feature of the DataGrid (for GridView in asp.net2.0): paging. If the DataGrid allows paging, it downloads only one page of data at a time, and it has a navigation bar for data paging, which lets you choose to browse a page and download only one page of data at a time.

But it has a small drawback that you have to bind all the data to the DataGrid. That is, your data layer must return all the data, and the DataGrid will then display the data needed to filter out the current page according to the current page. If there is a result set of 10,000 records to be paged with the DataGrid, assuming that the DataGrid displays only 25 data per page, it means that 9,975 data is discarded for each request. This large data set is returned for each request, and the performance impact on the application is significant.

A good solution is to write a paged stored procedure,
Such as:

CREATE PROCEDURE Dbo.sp_datapages
@Sql NVARCHAR (2000),
@PK varchar (50),--Primary key field name (can be any data type; not, and does not need to have a table name prefix, such as: cannot be users.id)
@Order varchar (50),--the Sort method (with DESC or ASC, can be multiple combinations; not, and does not need to have a table name prefix, such as: Users.id desc is not possible)
@Page int,
@PageSize int = 30
As

SET NOCOUNT ON

DECLARE @Str NVARCHAR (4000)

if (@Page =1)
SET @Str = ' Select Top ' + CAST ((@PageSize) as VARCHAR ()) + ' * FROM (' + @Sql + ') as Table1 Order by table1. ' + @Order
Else
SET @Str = ' Select Top ' + CAST ((@PageSize) as VARCHAR ()) + ' * FROM (' + @Sql + ') as table1 Where table1. ' + @PK + ' not In (Select Top ' + CAST ((@PageSize * (@Page-1) as VARCHAR) + "+ @PK + ' from (' + @Sql + ') as table2 Order by table 2. ' + @Order + ') Order by table1. ' + @Order

--print @str
--exec (@Str)
EXEC sp_executesql @Str

SET NOCOUNT OFF

Go

Alternatively, use the Row_number () function in SQL Server 2005

DECLARE @sql varchar (8000)


Set @sql = ' SELECT * '
+ ' from '
+ ' ('

+ ' Select Row_number () over (order by id desc) as rownumber,* '
+ ' from Users '
+ ' where id>0 and name<> ' '

+ ') '
+ ' as Table1 '

+ ' where rowNumber between ' +str ((@page-1) * @pagesize + 1) + ' and ' +str (@page * @pagesize)
+ ' ORDER BY id DESC '

--exec (@sql)
EXEC sp_executesql @sql

(Tip: Keep the total number of records as cache or session to improve paging performance.) )

7. Do not disable buffering of Web forms pages

Leave the buffer open unless you have a special reason to turn it off. Disabling buffering of Web forms pages can result in a lot of performance overhead.

Enable buffer for page output
If the buffer mechanism is closed, you can open it in the following way.
To open a page output cache using a program:
Response.bufferoutput = true;

Use the @page switch to turn on the page output buffering mechanism:
<%@ page Buffer = "true"%>

Use the <pages> node for the Web. config or machine.config configuration file:
<pages buffer= "true"/>

8. Set the smart navigation property of page

Smart navigation is set to true to improve the user's perceived performance. When this property is enabled, it has little impact on the client and the server. It intelligently refreshes the parts that need to be refreshed.

In most cases, do not set this property in your code.
Set the SmartNavigation property to True in the @ Page directive of the. aspx file. When the page is requested, the dynamically generated class sets the property.

When an Internet Explorer 5 or later browser requests a page (or later), smart navigation improves the user's ability to manipulate the page by performing the following functions:
Eliminates flicker caused by navigation.
Keep scrolling position when moving from one page to another.
Maintains the element focus between navigation.
Only the state of the last page is preserved in the browser's history.

Smart navigation is best for an ASP. NET page that requires frequent postbacks, but whose content does not change significantly when it returns. Consider this carefully when deciding whether to set this property to True.


Third, C # (or vb.net) program improvements

1. tostring Method using value type

When you connect strings, you often use the "+" sign to add numbers directly to a string. This method, while simple, can get the correct results, but because of the different data types involved, the numbers need to be converted to reference types by boxing to be added to the string. However, boxing operations have a large impact on performance because, when such processing occurs, a new object is assigned to the managed heap and the original value is copied to the newly created object.

Use the ToString method of a value type to avoid boxing operations, which can improve application performance.

int num=1;
String str= "Go" +num. ToString ();


2, the use of StringBuilder class

The string class object is immutable, and the re-assignment of a string object is essentially a re-creation of a string object and assigning the new value to the object, and its method of ToString does not significantly improve performance.

When working with strings, it is best to use the StringBuilder class, whose. NET namespace is system.text. Instead of creating a new object, the class directly operates on the string using methods such as Append,remove,insert and returns the result of the operation through the ToString method.

The definitions and operation statements are as follows:

int num;

System.Text.StringBuilder str = new System.Text.StringBuilder (); Create a string

Str. Append (Num. ToString ()); Add Value num

Response.Write (str. ToString); Show Operation results


3. Use the HttpServerUtility.Transfer method to redirect between pages in the same application

Using the Server.Transfer syntax, use this method in the page to avoid unnecessary client redirection (Response.Redirect).

4, avoid using ArrayList.

Because any object that is added to the ArrayList is to be marshaled to the System.Object type, when the data is fetched from ArrayList, it is disassembled back to the actual type. It is recommended that you use a custom collection type instead of ArrayList. ASP. NET 2.0 provides a new type, called Generics, which is a strong type that uses generic collections to avoid the occurrence of bins and unboxing and improves performance.

5. Use Hashtale instead of other dictionary collection types
(such as stringdictionary,namevaluecollection,hybridcollection), HashTable can be used when storing small amounts of data.

Reprint to http://blog.csdn.net/t_long/article/details/5610186

. NET program Optimization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.