Status Management
Data Access
Web Applications Program
Coding practices
Page and Server Control Processing
The following guidelines provide suggestions for the effective use of ASP. NET pages and controls.
1. Avoid unnecessary round-trip to the server. In some cases, you do not need to use ASP. NET Server controls and execute sending back events. 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 Code In this way, the page performance can be improved and the user experience can be improved. You can also use the client callback to read data from the server instead of performing the entire round-trip. For more information, see implement client callback programmatically without sending back on the ASP. NET webpage.
2. If you develop custom server controls, consider making them present client code for browsers that support ecmascript (JavaScript. By using server controls in this way, you can significantly reduce the number of times information is sent to the web server. For more information, see develop custom ASP. NET Server controls.
3. use the ispostback attribute of the page object to avoid unnecessary processing of the round-trip. If you write the code that processes the Server Control sending back, sometimes the code may only need to be executed at the first request page, instead of executing the command every time the request is sent back. Use the ispostback attribute to execute code conditionally based on whether the page is generated in response to the server control event.
4. You only need to save the automatic view status management of the server control view when necessary so that the server control can 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, as shown in the following DataGrid Server Control example:
Copy code 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 the page back to the server:
Copy code
Note: The @ control command also supports the enableviewstate attribute to specify whether the view State is enabled for the user control.
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. For more information about tracing and how to enable it, see ASP. NET tracing.
5. Unless buffering is disabled for some special reasons, disabling ASP. NET webpage buffering will cause a lot of performance overhead. For more information, see buffer attributes.
6. Use a transfer server object or cross-page sending method to redirect between different ASP. NET pages in the same application. For more information, see redirect users to another page.
Status Management
The following guidelines provide suggestions for effective status management.
When the session status is not used, not all applications or pages require the session Status of the specific user. You should disable the session status when you do not need the session status. To disable the page session Status, set the enablesessionstate attribute in the @ page command to false, as shown in the following example:
Copy code
Note: If the page needs to access session variables but does not create or modify them, set the enablesessionstate attribute in the @ page command to readonly.
You can also disable the session Status of the XML Web Services method. For more information, see XML Web Services created using ASP. NET and XML Web Services Client.
To disable the session Status of an application, set the mode attribute to off in the sessionstate section of the application's web. config file, as shown in the following example:
Copy code
Select the appropriate session Status provider ASP. NET provides a variety of methods for storing application session data: in-process session Status, out-of-process session status as a Windows service, and out-of-process session Status in the SQL Server database. (You can also create a custom session Status provider to store session data in the selected data storage area .) Each method has its own advantages, but the in-process session status is the fastest solution so far. If you only store a small amount of data that is prone to loss in the session state, we recommend that you use in-process providers. The out-of-process session status option is used to scale applications across multiple processors or computers, or to retain session data when a server or process restarts. For more information, see ASP. NET session status.
Data Access
The following guidelines provide recommendations for effective data access in applications.
1. use SQL Server and stored procedures for data access in. 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. For information on using SQL Server Stored Procedures, see configuration parameters (ADO. net ).
2. Use the sqldatareader class for the quick data-only cursor sqldatareader class to provide only 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. For more information, see sqldatareader class. For information about how ASP. NET accesses data, see access data through ASP. NET.
3. Try to cache data and page output ASP. NET provides some mechanisms that cache the output or data of these pages when you do not need to dynamically calculate page output or data for each page request. In addition, by designing pages and data requests to be cached (especially in areas where the site is expected to have a large amount of communication), you can optimize the performance of these pages. Compared with any other functions of. NET Framework, using the cache appropriately can improve the performance of the website.
4. 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. Using the "cache total turnover rate" (total cache circulation rate) performance counter associated with the "ASP. NET Applications" performance object, you can monitor the cache turnover caused by the expiration of items. High turnover rate may indicate problems, especially when items are removed before expiration. (This is sometimes called memory pressure .)
For information about how to cache page output and data requests, see ASP. NET cache overview.
The SQL cache dependency ASP. NET supports table-based round robin and query notifications, depending on the version of the SQL Server in use. 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.
For more information about SQL cache dependencies, see Walkthrough: use ASP. net output cache in combination with SQL Server or use the sqlcachedependency class to cache in ASP. NET.
The UI paging function of data controls such as data source paging and sorting instead of UI (User Interface) paging and sorting 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.
Balance the security benefits and performance overhead of event verification from system. web. UI. webcontrols and system. web. UI. controls derived from the htmlcontrols class can verify whether 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 data from being processed and manipulated by a delete call (which is essentially not supported in the control. 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.
Security Description: 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.
Unless necessary, do not use view State encryption. view State encryption prevents users from reading values in hidden view State fields. 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.
Use sqldatasource 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 control's filtering and sorting operations (configured using the filterexpression and sortparametername attributes) will use the cached data. In many cases, if the entire dataset is cached and the filterexpression and sortparametername attributes are used for sorting and filtering, instead of using SQL queries with "where" and "sort by" clauses (for these queries, each selection operation requires access to the database), the application runs faster.
Web Applications
The following guidelines provide suggestions for the entire web application to work effectively.
Consider pre-compilation in the first request to resources (such as ASP. NET web pages), web applications are batch compiled. If no pages are compiled in the application, the batch compilation function will compile all pages in the directory in batches to increase disk and memory usage. You can use ASP. NET compilation tool (aspnet_compiler.exe) to pre-compile web applications. For local compilation, this compilation tool calls the ASP. NET Runtime Library to compile the site. The method is the same as when you request a page from the website. Web applications can be pre-compiled to retain the UI tag, or pages can be pre-compiled to prevent changes Source code . For more information, see How to: precompile ASP. NET web sites: Pre-compile an ASP. NET Website.
On Internet Information Service 5.0, when a web application runs out of process, ASP. NET on IIS 5.0 uses the out-of-process auxiliary process to provide services for requests by default. This feature has been optimized to increase throughput. It is recommended to use ASP. net on the production site because it has its functions and advantages in the auxiliary process outside the process.
Regular recovery processes should be recycled regularly to ensure both stability and performance. After a long period of time, resources with memory leaks and bugs can affect the Web server throughput, while the recycle process can clear the memory to avoid such problems. However, the demand for regular recovery and frequent recovery should be balanced, because the overhead of stopping auxiliary processes, reloading pages, and re-obtaining resources and data may exceed the benefits of recovery.
You do not need to adjust the process model settings for ASP. NET web applications running on Windows Server 6.0 using IIS 2003 because ASP. NET uses the IIS 6.0 process model settings.
If necessary, adjust the number of threads for each auxiliary process of the application asp. NET Request structure to try to strike a balance between the number of threads executing requests and available resources. This structure determines the number of requests that can be executed simultaneously based on the CPU power available for requests. This technology is called thread-control. But under some conditions Algorithm Not very effective. By using the "pipeline instance count" (pipeline instance count) performance counter associated with the "ASP. NET Applications" performance object, you can monitor thread-control in Windows performance monitor.
When an ASP. NET web page calls external resources (for example, when a database access or XML Web Services request is executed), the page request usually stops and releases the CPU to process other threads until the external resource responds. If another request is waiting for processing and a thread in the thread pool is released, it starts to process the waiting request. This may cause ASP. there are a large number of concurrent requests and many waiting threads in the net auxiliary process or application pool, and they will affect the Web server throughput and thus adversely affect the performance.
To alleviate this problem, you can manually set the number of threads in the process by changing the maxworkerthreads and maxiothreads attributes in the processmodel section of the machine. config file.
Note: The auxiliary thread is used to process ASP. NET requests, while the IO thread is used to provide services for data from files, databases, or XML Web Services.
The value assigned to the process model attribute is the maximum number of threads of each CPU type in the process. For dual-processor computers, the maximum number is twice the set value. For a four-processor computer, the maximum value is four times the set value. The default value can be used for computers with one or two processors. However, for computers with more than two processors, 100 or 200 threads in a process may cause more disadvantages. Because of the extra context switch, the operating system spends the CPU cycle on the maintenance thread rather than processing the request, so too many threads in the process will often reduce the server speed. The proper number of threads should be determined through the performance test of the application.
For applications that rely heavily on external resources, consider enabling web gardening ASP on a multi-processor computer. the. NET process model helps enable scalability on a multi-processor computer by distributing work to multiple processes (one per CPU), and each process sets the processor Association to a CPU. This technology is called Web gardening. Enable Web gardening for your application if your application uses a slow database server or calls a COM Object with external dependencies (only two possibilities are mentioned here. However, before deciding to enable Web gardening for production sites, you should test the implementation of applications in the Web garden.
Disable debug mode: Always Disable debug mode before deploying production applications or performing any performance measurements. If the debug mode is enabled, the performance of the application may be affected. For more information about setting the syntax for debugging mode, see edit ASP. NET configuration file.
Optimize the configuration files for Web server computers and specific applications to meet your needs. By default, Asp.. Net configuration is set to enable the most extensive feature set and try to adapt to the most common situations. You can change some default configuration settings to improve application performance, depending on the features you use. The following list contains the configuration settings you should consider:
By default, ASP. NET applications use Windows Authentication mode or integrated NTLM. In most cases, it is best to disable authentication only for applications that require authentication in the machine. config file and enable authentication in the web. config file.
Configure the application ASP. Net default encoding format as UTF-8 based on the appropriate request and response encoding settings. If your application only uses ASCII characters, configure your ASCII application for a slight performance improvement.
To disable autoeventwireup for an application, set the autoeventwireup attribute to false in the machine. config file, which means that the page will not bind page events to name-matching methods (such as page_load ). If autoeventwireup is disabled, the page will be slightly improved by leaving the event connection to you instead of automatically executing it.
To process page events, you can use either of the two policies. The first policy is to override the methods in the base class. For example, you can rewrite the onload method of the page object for the page loading event, instead of using the page_load method. (You must call the base method to ensure that all events are triggered .) The second method is to bind the handles keyword in Visual Basic or the delegate connection in C # to the event.
Remove unused modules from the request processing pipeline. By default, all functions of the httpmodules node in the machine. config file of the server computer are kept active. Based on the features used by the application, you can remove unused modules from the request pipeline for a slight performance improvement. Check each module and its functions and customize it as needed. For example, if you do not use session Status and output cache in an application, you can remove them from the httpmodules list so that requests do not perform other meaningful processing, you do not have to call these modules.
The following coding practices provide suggestions for writing valid code.
Do not rely on exceptions in the code to 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. The following example shows the code that may cause exceptions and test whether code in a certain status exists. The two generate the same results.
C # copy the code // This is not recommended.
Try {
Result = 100/num;
}
Catch (exception e ){
Result = 0;
}
// This is preferred.
If (num! = 0)
Result = 100/num;
Else
Result = 0;
Copy the code 'this is not recommended in Visual Basic. try result = 100/numcatch (E as exception) Result = 0end try 'this is preferred. if not (num = 0) Result = 100/numelse result = 0end if
In managed code, rewrite and call-intensive COM components. 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.
By default, ASP. NET does not allow the Stas COM component to run on pages. 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. In addition, avoid creating the sta COM component during the construction of the page. For example, in the following code, samplestacomponent created by a thread will be instantiated during page construction, and this thread is not the sta thread running the page. This may have a negative impact on the performance, because to construct a page, you need to mail between the MTA and the sta thread.
Copy code
Response. Write (server. htmlencode (mycomp. sayhello ))
%>
The preferred mechanism is to postpone object creation until the above code is executed in the sta thread, as shown in the following example:
Copy code
Response. Write (server. htmlencode (mycomp. sayhello ))
%>
We recommend that you construct COM components and external resources only 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.