Encoding for ASP. NET performance optimization

Source: Internet
Author: User

The following describes how to optimize ASP. NET performance in coding.

Processing of pages and server controls for ASP. NET performance optimization

A) Avoid unnecessary round trips to the server

In some cases, you do not need to use the ASP. NET Server Control and execute the send-back event processing. For example, verifying user input on an ASP. NET webpage can often be performed on the client before the data is submitted to the server. Generally, if you do not need to pass the information to the server for verification or write it into the data storage area, avoid using the code that causes the round-trip to the server, this improves the page performance and user experience. You can also use the client callback to read data from the server instead of performing the entire round-trip.

The page class implements the ICallbackEventHandler interface and registers the GetCallbackEventReference method, that is, ajax callback implementation.

For a page that requires loading many controls (loading time-consuming pages), we can use ajax technology to improve page access performance.

B) Use the IsPostBack attribute of the Page object to avoid unnecessary handling of the round trip

If you write the code that processes the Server Control sending back, sometimes the code may only be executed on the first request page, instead of every sending back. Use the IsPostBack attribute to execute code conditionally based on whether the page is generated in response to the server control event.

Place the code that needs to be executed when the page is requested for the first time in the IsPostBack condition.

C) only save the Server Control view status when necessary

The automatic view status management enables the server controls to re-fill their attribute values during the round-trip, without writing any code. However, this function affects performance because the view status of the server control is redirected to and from the server in the hidden form field. It is helpful to 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 on each round trip, because the value of the control will be replaced with a new value during data binding, the saved view status is useless. In this case, disabling the view State can save processing time and reduce the page size.

By default, view status is enabled for all server controls. To disable it, set the EnableViewState attribute of the control to false.

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.

The @ Control command also supports the EnableViewState attribute to specify whether the view State is enabled for the user Control.

View status:

To analyze the size of the view State used by the server control in the Page, enable tracing for this Page by including the trace = "true" attribute in the @ Page command. Then, in the trace output, view the "Viewstate" column in the "control hierarchy" table.

Viewstate can be disabled in the following cases:

1) Page Control. ascx)

2) The page is not returned to itself.

3) You do not need to process control events.

4) The control does not have dynamic or data-bound attribute values or is processed in the code for each postpack)

D. Keep the buffer in the open State unless it is disabled for special reasons.

Disabling the buffer of ASP. NET web pages results in a large amount of performance overhead.

E) Server. Transfer and Response. Redirect

Response. Redirect simply tells the browser to access another page. Server. Transfer helps reduce Server requests and keep the address bar URL unchanged. It allows you to pass the query string and form variables to another page to hide the parameters passed in the url.

Response. Redirect can jump across sites, and Server. Transfer can only jump to the same site.

Microsoft recommends:

Redirect between different ASP. NET pages in the same application using a Transfer Server object or cross-page sending Method

If there are no special requirements, Server. Transfer should be selected first for page Jump

ASP. NET performance optimization-Data Access

A) use SQL Server and stored procedures for data access

Among all the data access methods provided by. NET Framework, using SQL Server for 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 SQL commands as much as possible for additional performance improvement.

Select SQL Server only for the database. If the database is another one, ignore this option)

B) Use the SqlDataReader class for fast data-only cursor

The SqlDataReader class provides only inbound data streams retrieved from the SQL Server database. If you can use read-only streams in ASP. NET applications, the SqlDataReader class provides higher performance than the DataSet class. The SqlDataReader class uses the Local Network Data Transmission Format of SQL Server to directly read data from the database connection. For example, when bound to the SqlDataSource control, you can achieve better performance by setting the DataSourceMode attribute to DataReader. Using a data reader may lead to loss of some features .) In addition, the SqlDataReader class implements the IEnumerable interface, which allows you to bind data to server controls.

(Select SQL Server only for the database. If the database is another one, you can ignore this option.) MySql corresponds to MySqlDataReader and select as needed.

C) cache data and page output as much as possible

ASP. NET provides some mechanisms to cache the output or data of these pages when you do not need to request dynamic computing page output or data for each page. In addition, you can optimize the performance of pages and data requests to be cached, especially in areas where the site is expected to have a large amount of communication. Compared with any other functions of. NET Framework, using the cache appropriately can improve the performance of the website.

Note the following when using ASP. NET cache. First, do not cache too many items. Each item in the cache has a memory overhead. Do not cache items that are easy to recalculate and rarely used. Second, the period of validity allocated to cache items should not be too short. Items that expire soon will cause unnecessary turnaround in the cache, and cause additional code clearing and garbage collection. You can use the "Cache Total Turnover Rate" Cache Total circulation Rate associated with the "ASP. NET Applications" performance object) performance counters to monitor the Turnover caused by expiration of items in the Cache. High turnover rate may indicate problems, especially when items are removed before expiration. This is sometimes called memory pressure .)

You can consider putting static, slightly changed, or infrequently changed content that requires dynamic loading into the control and using the cache technology.

<% @ OutputCache Duration = "100" VaryByParam = "none" %>

D) use SQL cache dependencies appropriately

ASP. NET also supports table-based round robin and query notifications, depending on the version of the SQL Server used. All SQL Server versions support table-based round robin. In table-based round robin, if any content in the table is changed, all listeners will become invalid. This may cause unnecessary changes in the application. We recommend that you do not use table-based round robin For tables with many frequent changes. For example, we recommend that you use table-based round robin for directory tables with few changes. We recommend that you do not use table-based round robin For order tables. Order tables are updated more frequently. SQL Server 2005 supports query notifications. Query notifications support specific queries to reduce the number of notifications sent when the table is changed. Although it provides better performance than table-based round robin, it cannot be extended to accommodate thousands of queries.

(Select SQL Server only for the database. If the database is another one, you can ignore this option)

E) Use Data Source paging and sorting instead of UI User Interface) paging and sorting

The UI paging function of data controls such as DetailsView and GridView can be used to support any data source objects of the ICollection interface. For each paging operation, the Data Control queries the entire dataset of the data source, selects the row to be displayed, and discards the remaining data. If the data source implements performanceview and the CanPage attribute returns true, the data control uses the data source paging instead of the UI paging. In this case, the data control only queries the rows required for each paging operation. Therefore, data source paging is more efficient than UI paging. Only the ObjectDataSource data source control supports data source paging. To enable data source paging on other data source controls, you must inherit from the data source control and modify its behavior.

F) balance the security benefits and performance overhead of event Verification

Controls derived from the System. Web. UI. WebControls and System. Web. UI. HtmlControls classes can verify that the event is derived from the user interface presented by the control. This helps prevent the control from responding to forged Event Notifications. For example, the DetailsView control can prevent Delete operations. The call control does not support this operation in nature. This verification results in certain performance overhead. You can use the EnableEventValidation configuration element and the RegisterForEventValidation method to control this behavior. The overhead of the verification depends on the number of controls on the page, which is within a few percent.

We strongly recommend that you do not disable event verification. Before disabling event verification, make sure that no sending back that may have an unexpected impact on the application is constructed.

G) do not use view State encryption unless necessary

View state encryption prevents users from reading values in the hidden view State field. A typical scenario is the GridView control with an Identifier Field in the DataKeyNames property. The Identifier Field is required to coordinate record updates. Because you do not want the identifier to be visible to the user, you can encrypt the view status. However, encryption has a constant performance overhead for initialization and additional overhead depending on the size of the encrypted view State. Encryption is set for each page load, so the same performance impact occurs during each page load.

H) Use SqlDataSource for caching, sorting, and filtering

If the DataSourceMode attribute of the SqlDataSource control is set to DataSet, SqlDataSource can cache the query result set. If data is cached in this way, the filter and sort operations of the control are configured using the FilterExpression and SortParameterName attributes. The cached data is used. In many cases, if you cache the entire dataset and use the FilterExpression and SortParameterName attributes for sorting and filtering, instead of using SQL queries with the "WHERE" and "SORT BY" clauses for these queries, the application runs faster.

(Only some databases are supported based on specific controls)

Encoding practices for ASP. NET performance optimization

A) do not rely on exceptions in the code

Exceptions greatly reduce performance, so you should avoid using them as a way to control normal program streams. If the code may cause an exception, perform this operation instead of capturing and processing the exception. Common Code detection solutions include checking null, assigning a value to a String that will be analyzed as a value, or checking a specific value before applying a mathematical operation.

B) rewrite the calling-intensive COM component in the managed code

. NET Framework provides a simple way to interact with traditional COM components. The advantage is that the. NET function can be used while retaining the existing COM component investment. However, in some cases, retaining the performance overhead of the old component makes it worthwhile to migrate the component to the managed code. Every situation is different. The best way to determine whether to migrate components is to measure the website running performance. We recommend that you study how to migrate any frequently called COM components to managed code.

In many cases, it is impossible to migrate legacy components to managed code, especially when a Web application is initially migrated. In this case, one of the biggest performance barriers is to mail data from an unmanaged environment to a hosted environment. Therefore, in interactive operations, perform as many tasks as possible at any end, and then perform a single call instead of a series of small calls. For example, all strings in the Common Language Runtime Library are Unicode, so all strings in the component should be converted to Unicode format before calling managed code.

Once any COM objects or local resources are processed, release them. In this way, other requests can use them and minimize the performance problems caused by later requests to the garbage collector to release them.

C) Avoid single-threaded unit (STA) COM components

By default, ASP. NET does not allow the sta com component to run on the page. To run them, you must include the ASPCompat = true attribute in the. aspx file in the @ Page command. In this way, the thread pool used for page execution is switched to the STA thread pool, and HttpContext and other built-in objects can be used for COM objects. Avoiding the use of the sta com component is a performance optimization because it avoids any call to mail the multi-thread unit (MTA) to the STA thread.

If you must use the sta com component, avoid calling a large number during execution and try to send as much information as possible during each call. The preferred mechanism is to postpone object creation. We recommend that you only construct COM components and external resources when necessary or in the Page_Load method.

Never store the sta com component in shared resources such as cache or session status that can be accessed by other threads other than the threads that construct them. Even if the STA thread calls the sta com component, only the thread that constructs the sta com component can serve the call, and this requires sending and processing calls to the Creator thread. This mail may cause significant performance loss and scalability problems. In this case, consider making the COM component an mta com component or overwriting the component in the managed code.

This article is from shllove's column ASP. NET performance optimization.
  1. ASP. NET Performance Optimization Configuration
  2. The simplest ASP. NET performance monitoring tool
  3. Some misunderstandings about. NET performance and the relationship between C # and VB. NET
  4. Lambda expressions: Do you need clear code for performance?
  5. Analysis of methods to improve the performance of GDI Programming

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.