[Recommended] seven aspects of. NET Program Performance Optimization

Source: Internet
Author: User
Tags add numbers

I. Database Operations

1. Close the database connection immediately after use

To access database resources, you need to create a connection, open a connection, and close the connection. These processes need to exchange information with the database multiple times to pass identity authentication, which consumes server resources.

Source. ASP. NET provides a Connection Pool to improve the impact of enabling and disabling databases on performance. The system places the user's database connection in the connection pool. If necessary, the connection is taken out. When the connection is closed, the connection is withdrawn and the next connection request is waited.

The size of the connection pool is limited. If you still need to create a connection after the connection pool reaches the maximum limit, the performance will be greatly affected. Therefore, after a database connection is established, the connection is enabled only when operations are required. The connection is closed immediately after use, so as to minimize the time for opening the database connection and avoid exceeding the connection limit.

Usage (recommended)
Using (SqlConnection Conn = new SqlConnection (connstr ))
{} // Do not show off

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

2. Use stored procedures whenever possible and Optimize Query statements

Stored procedures are a set of pre-compiled SQL statements stored on the server, similar to the batch processing files in the DOS system. Stored Procedures provide the ability to access databases immediately and process information quickly. Using the stored procedure can avoid multiple compilation of commands. After one execution, the execution plan will reside in the cache. In the future, you only need to directly call the binary code in the cache. Among all data access methods provided by. NET Framework, SQL Server-based data access is a recommended choice for generating high-performance, scalable Web applications. When using a hosted SQL Server Provider, you can use compiled stored procedures instead of special queries to obtain additional performance improvements.

In addition, the stored procedure runs on the server and is independent from the ASP. NET program to facilitate modification. The most important thing is that it can reduce the transmission of database operation statements over the network.

Optimize Query statements

In ASP. NET, the ADO connection consumes a considerable amount of resources. The longer the SQL statement runs, the longer the system resources are occupied. Therefore, try to use optimized SQL statements to reduce execution time. For example, if a query statement does not contain a subquery statement, only useful data and fields should be returned as much as possible to make full use of indexes.

3. Use SqlDataReader for read-only data access. Do not use DataSet.

The SqlDataReader class provides a method for reading data streams only retrieved from the SQL Server database. If you are allowed to use an ASP. NET application when creating it, The SqlDataReader class provides higher performance than the DataSet class. This is because SqlDataReader uses the Local Network Data Transmission Format of SQL Server to directly read data from the database connection. In addition, the SqlDataReader class implements the IEnumerable interface, which allows you to bind data to server controls. As a powerful and offline database, DataSet has a relatively high performance cost.

Sqldataread advantages: fast data reading. If you do not need to process the returned data in large quantities, we recommend that you use SqlDataReader. Its performance is much better than that of datset. Disadvantage: the connection to the database cannot be closed until the data is read.

Dataset reads data and caches it in the memory. Disadvantage: High memory usage. If a large amount of processing is required for the returned data, it is better to use Dataset to reduce the connection operations to the database. Advantage: Only one connection is required to close the connection to the database.

Generally, SqlDataReader is used to read a large amount of data and not process the returned data in large quantities. It is more appropriate to use datset to process a large amount of returned data. The selection of SqlDataReader and Dataset depends on the implementation of program functions.

4. Data Binding DataBinder

General Binding method <% # DataBinder. Eval (Container. DataItem, "field name") %>

Binding with DataBinder. eval does not require concern about the data source (read or dataset ). The data type eval will convert the data object into a string. It does a lot of work on the underlying binding and uses the reflection performance. This is because it is easy to use, but affects data performance.

Let's see <% # DataBinder. Eval (Container. DataItem, "field name") %>. When dataset is bound, DataItem is actually a DataRowView (if it is bound to a data reader (dataread), it is an IdataRecord .) Therefore, directly converting to DataRowView will greatly improve the performance.

<% # Ctype (Container. DataItem, DataRowView). Row ("field name") %>

We recommend that you use <% # ctype (Container. DataItem, DataRowView). Row ("field name") %> to bind data. Pay attention to the following two aspects during use:
1. Add <% @ Import namespace = "System. Data" %>.
2. Pay attention to the Case sensitivity of field names ). If it is inconsistent with the query, it may be slower than <% # DataBinder. Eval (Container. DataItem, "field name") %> in some cases. To further increase the speed, you can use the <% # ctype (Container. DataItem, DataRowView). Row (0) %> method. But its readability is not high.

The above is the vb.net method. In c #: <% # (DataRowView) Container. DataItem) ["field name"] %>

5. Multiple result sets are returned.

Whether SqlDataReader or datset, multiple result sets are returned. Then, rd. NextResult () or ds. Tables [I] is used to process the data separately, reducing the number of times the database is reconnected. At the same time, try to replace complicated DataSet secondary processing with more efficient SQL statements.

Ii. Page Optimization

1. Unnecessary Server Control)

In ASP.net, a large number of server-side controls facilitate program development, but may also lead to performance loss, because each time a user operates a server-side control, a round-trip process with the server is generated. Therefore, Server Control should be used less unless necessary. In many other cases, rendering or data binding is more effective than using server controls, even when using server control templates. However, if you want to programmatically manipulate the properties of the server control, process server control events, or save the view status, use the server control as appropriate.

Therefore, select the html control whenever possible. Functions that can be implemented on the client are implemented on the client (proficient in javascript) to reduce the pressure on the server.

2. Do not use unnecessary ViewState

By default, ASP. Net enables ViewState (view State) for all Server Control ). However, ViewState needs to save some information on the client, which may cause performance consumption. If you must use Server Control, you can disable ViewState.
Only save the Server Control view status when necessary. Automatic view status management is a function of the server control. This function enables the Server Control to re-fill their attribute values during the round-trip process (you do not need to write any code ). However, because the view status of the server control is redirected to and from the server in the hidden form field, this function does have an impact on performance. You should know under which circumstances the view status will be helpful and under which circumstances it will affect the page performance. For example, if you bind a server control to data during each round-trip process, the new value obtained from the data binding operation replaces the saved view status. In this case, disabling the view status can save processing time.

By default, view status is enabled for all server controls. To disable view status, set the EnableViewState attribute of the control to false, as shown in the following DataGrid Server Control example.

<Asp: datagrid EnableViewState = "false" runat = "server"/>
You can also use the @ Page command to disable the view status of the entire Page. This is useful when you do not send a Page back to the server: <% @ Page EnableViewState = "false" %>

Note that the @ Control command also supports the EnableViewState attribute, which allows you to Control whether the view State is enabled for the user Control.
To analyze the number of view States used by the server control on the Page, please (include the trace = "true" attribute in the @ Page command) enable tracing on this page and view the Viewstate column of the Control Hierarchy table.

3. Avoid unnecessary round-trip to the server

Although you may want to use the time-saving and code-saving functions of the Web forms page framework as much as possible, ASP. NET Server controls and sending back events cannot be used in some cases.

Generally, you only need to start the round-trip process to the server when retrieving or storing data. Most data operations can be performed on clients during the round-trip process. For example, it is often possible to verify user input from an HTML form on the client before the data is submitted to the server. Generally, if you do not need to pass the information to the server to store it in the database, you should not write the code that leads to the round-trip process.

If you develop custom server controls, consider making them present client code for browsers that support ECMAScript. By using the server control in this way, you can significantly reduce the number of times information is not necessary to be sent to the Web server.

Use Page. IsPostBack to avoid unnecessary operations on the round-trip Process

If you write the code for processing the Server Control sending and processing, you may sometimes need to execute other code on the first request page, instead of the Code executed when the user sends an HTML form contained in the page. Use the Page. IsPostBack attribute to execute code conditionally based on whether the Page is generated in response to the server control event. For example, the following code demonstrates how to create a database connection and command. This command binds data to the DataGrid server control when you request this page for the first time.

Void Page_Load (Object sender, EventArgs e)
{
If (! Page. IsPostBack)
{}
}

Because the Page_Load event is executed during each request, the code above checks whether the IsPostBack attribute is set to false. If yes, the code is executed. If this attribute is set to true, no code is executed.

Note that if you do not run this check, the page sending behavior will not be changed. The code of the Page_Load event is executed before the Server Control event is executed, but only the results of the server control event can be displayed on the output page. If you do not run this check, the Page_Load event and any server control event on the page will still be processed.

4. Disable the Session when the Session status is not used, and use as few sessions as possible during program development.

Not all applications or pages need to be specific to the user's session status. You should disable the session status for any applications or pages that do not need the session status.

To disable the Page session Status, set the EnableSessionState attribute in the @ Page command to false. Example: <% @ Page EnableSessionState = "false" %>

Note: If the Page needs to access session variables without creating or modifying them, set the EnableSessionState attribute in the @ Page command to ReadOnly.

To disable the session Status of an application, set the mode attribute to off in the sessionstate configuration section of the Application Web. config file. Example: <sessionstate mode = "off"/>

5. Use the DataGrid properly (in asp. net2.0, The GridView Control)

The DataGrid Control has the most powerful data display function and has many built-in functions such as data modification, deletion, addition, and paging. If you only need to simply display the data, the DataGrid is not the best choice. The paging function and data storage method of the DataGrid Control (stored in viewstate) make it easy and convenient for program developers to use, but the resulting performance overhead is not negligible.

The DataList control has much fewer functions than the DataGrid Control. However, the customization is much stronger. The unique multi-row data display is more convenient. The functions that the DataGrid can implement.

The Repeater control has the least functions, but is very user-defined. Due to the reduction of many functions, the performance of the server is minimized.

Therefore, when you simply need to display the data list, you can select the Repeater or DataList control to achieve the same purpose and reduce the performance overhead.

Recommended sequence: Repeater and DataList last DataGrid (GridView)

6. Paging data

The ASP. NET DataGrid (in asp. net2.0, The GridView) has a very useful function: paging. If the DataGrid allows paging, it only downloads data on a certain page at a certain time. In addition, it has a data paging navigation bar, which allows you to choose to browse a certain page, in addition, only one page of data is downloaded at a time.

But it has a small drawback: You must bind all the data to the DataGrid. That is to say, your data layer must return all the data, and the DataGrid then filters out the data needed for the current page based on the current page. If there is a result set with 10 thousand records to be paged using the DataGrid, assuming that only 25 data entries are displayed on each page of the DataGrid, it means that 9975 data entries are discarded in each request. Each request must return such a large dataset, which has a very high impact on the performance of the application.

A good solution is to write a paging storage process,
For example:

Create procedure dbo. sp_DataPages
@ SQL nVARCHAR (2000 ),
@ PK varchar (50), -- primary key field name (can be of any data type; no, and no table name prefix is required, such as: cannot be users. id)
@ Order varchar (50), -- sorting method (with desc or asc, it can be multiple combinations; no, and the table name prefix is not required. For example, it cannot be users. id desc)
@ Page int,
@ PageSize int = 30
AS

Set nocount on

DECLARE @ Str nVARCHAR (4000)

If (@ Page = 1)
SET @ Str = 'select Top '+ CAST (@ PageSize) As VARCHAR (20) +' * From ('+ @ SQL + ') as table1 Order By table1. '+ @ Order
Else
SET @ Str = 'select Top '+ CAST (@ PageSize) As VARCHAR (20) +' * From ('+ @ SQL + ') as table1 Where table1. '+ @ PK +' Not In (Select Top '+ CAST (@ PageSize * (@ Page-1) as varchar (20 )) + ''+ @ PK + 'From (' + @ SQL + ') As table2 Order By table2.' + @ 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

(TIPS: Keep the total number of records as Cache or Session to improve paging performance .)

7. Do not disable Web form page buffering.

Disable the buffer unless otherwise specified. Disabling Web form page buffering can cause a large amount of performance overhead.

Enable the Buffer for page output)
If the Buffer mechanism is disabled, use the following method.
Use a program to open the page output cache:
Response. BufferOutput = true;

Use the @ Page switch to enable the Page output buffer mechanism:
<% @ Page Buffer = "true" %>

Use the <pages> node of the Web. config or Machine. config configuration file:
<Pages buffer = "true"/>

8. Set the smart navigation attribute of the page.

Setting smart navigation to true can significantly improve user performance. Enabling this attribute has little impact on the client and server. It can intelligently refresh what needs to be refreshed.

In most cases, do not set this attribute in code.
Set the SmartNavigation attribute to true in the @ Page command of the. aspx file. When you request this page, the dynamically generated class sets this attribute.

When a browser requests a page (or later) in Internet Explorer 5 or later, intelligent navigation improves the user's ability to operate the page by executing the following functions:
Eliminate flickering caused by navigation.
Keep the scroll position when you move from one page to another.
Maintain the element focus between navigation.
Only the status of the last page is retained in the browser history.

Intelligent Navigation is most suitable for ASP. NET pages that require frequent sending back, but their content does not change significantly when it is returned. Consider this carefully when deciding whether to set this attribute to true.

C # (or vb.net) Program Improvement

1. Use the ToString method of Value Type

When connecting strings, you often use the "+" sign to directly add numbers to strings. This method is simple and can get the correct results. However, because different data types are involved, the numbers must be converted to the reference type through the boxing operation before they can be added to the string. However, the packing operation has a great impact on the performance, because during such processing, a new object will be allocated in the managed heap, and the original value will be copied to the newly created object.

The Value Type ToString method can be used to avoid packing and improve application performance.

Int num = 1;
String str = "go" + num. ToString ();

2. Use the StringBuilder class

The String class object cannot be changed. In essence, the re-assignment of the String object re-creates a String object and assigns the new value to the object, the ToString method does not significantly improve the performance.

When processing strings, it is best to use the StringBuilder class. Its. NET namespace is System. Text. This class does not create a new object, but directly performs operations on strings through Append, Remove, Insert, and other methods, and returns the operation results through the ToString method.

Its definition and operation statement are as follows:

Int num;

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

Str. Append (num. ToString (); // Add the numeric value num

Response. Write (str. ToString); // display the operation result

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

Use the Server. Transfer syntax to avoid unnecessary client redirection (Response. Redirect) by using this method on the page ).

4. Avoid using ArrayList.

Because any Object to be added to the ArrayList must be of the System. Object type. When retrieving data from the ArrayList, it must be split back to the actual type. We recommend that you replace ArrayList with a custom set type. Asp.net 2.0 provides a new type called generic, which is a strong type. Using a generic set can avoid the occurrence of binning and unpacking and improve the performance.

5. Use HashTale to replace other dictionary set types
(Such as StringDictionary, NameValueCollection, and HybridCollection). HashTable can be used to store a small amount of data.

 

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.