26 common performance optimization methods in Asp.net

Source: Internet
Author: User

1. database access performance optimization
 
Database Connection and Shutdown

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 for authentication, which consumes server resources. Provided in ASP. NET
Connection Pool (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 connection pool size 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 an operation is required. The connection is closed immediately after use,
In this way, we can minimize the time needed for database connection opening to avoid exceeding the connection limit.

Use stored procedures
 
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. Use Storage
The process can avoid multiple compilation of commands. After a command is executed, the execution plan will reside in the cache. You only need to directly call the binary code in the cache when necessary. In addition, stored procedures run on the server
The row is independent of ASP. NET programs for easy modification. The most important thing is that it can reduce the transmission of database operation statements in 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, a query statement that does not contain a subquery statement makes full use of indexes.

2. Optimized string operation performance
 
Use the tostring method of the Value Type
  
When connecting strings, you often use the "+" sign to directly add numbers to strings. Although this method is simple, you can get the correct results, but because of the different data types involved, numbers need to be packed
To be added to a 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.

Use 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. Its method is tostring.
Performance improvement is not significant. When processing strings, it is best to use the stringbuilder class, its. net
The namespace is system. Text. This class does not create a new object, but directly performs operations on strings through append, remove, insert, or other methods.
The tostring method returns the operation result. Its definition and operation statement are as follows:

Int num; system. Text. stringbuilder STR = new
System. Text. stringbuilder (); // create the str. append (Num. tostring () string ());
// Add the numeric num response. Write (Str. tostring); // display the operation result 3. Optimize the Web
Configuration files for server computers and specific applications to meet your specific needs

By default, ASP. NET configuration is set to enable the widest range of features and adapt to the most common solutions. Therefore, application developers can optimize and modify some of the configurations based on the features used by the application to improve application performance. The following lists some options you should consider.

Only enable authentication for the desired application.

By default, the authentication mode is windows, or NTLM is integrated. In most cases, it is recommended that the machine. config
Disable authentication and enable authentication in the web. config file. Configure the application based on the appropriate request and response encoding settings. The default encoding format of ASP. NET is
UTF-8. If your application is strictly ASCII, configure the application to use ASCII for a slight performance improvement.
  
Disable autoeventwireup for applications.

Set the autoeventwireup attribute
False means that the page does not match the method name and event or hook the two (for example
Page_load ). If page developers want to use these events, they need to override these methods in the base class (for example, they need to override the page loading event
Page. onload, instead of using the page_load method ). If disabled
Autoeventwireup, the page will be slightly improved by leaving the event connection to the page author instead of automatically executing it.

Remove unused modules from the request processing pipeline.

By default
All functions of the node are retained as activated. 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
Define it. For example, if you do not use session status or output cache in an application
Remove them from the list so that requests do not have to execute the entry and exit code for each module when no other meaningful processing is performed.

4. Disable the debugging mode.

Remember to 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 greatly affected.

5. For applications that rely heavily on external resources, consider enabling network gardening on a multi-processor computer.

ASP. NET process model helps enable scalability on a multi-processor computer, distributes work to multiple processes (one per CPU), and each process sets the processor relationship to its
CPU. This technology is called Web gardening. If the application uses a slow database server or calls a com with external dependencies
Object (only two possibilities are mentioned here), it is helpful to enable Web gardening for your application. However, before deciding to enable Web gardening, you should test how applications are executed in the Web garden.
  

6. cache data and page output whenever possible

ASP. NET
Some simple mechanisms are provided to cache the output or data of these pages when you do not need to dynamically compute the page output or data for each page request. In addition, by designing pages and data requests to be cached (especially on websites)
) To optimize the performance of these pages. Any web
Compared with the form function, the proper use of the cache can better improve the performance of the site, sometimes this increase is more than an order of magnitude. Use ASP. NET
There are two considerations for caching. First, do not cache too many items. Each item in the cache has an overhead, especially for memory usage. Do not cache items that are easy to recalculate and rarely used. Second, allocate cached items
Is not too short. Items that expire soon will result in unnecessary turnover in the cache, and often lead to more code cleanup and garbage collection work. If you are concerned about this issue, Please monitor it with ASP. NET
Applications performance object associated cache total turnover rate
Performance counters. High turnover rate may indicate problems, especially when items are removed before expiration. This is also called memory pressure.

7. Select a data view mechanism suitable for pages or applications

There are often important trade-offs between convenience and performance based on how you choose to display data on a web form page. For example, DataGrid Web
The server control may be a convenient and quick way to display data, but its overhead is often the largest in terms of performance. In some simple cases, you can generate an appropriate HTML
Rendering data by yourself may be very effective, but custom and browser targeting will quickly offset the extra benefits. Repeater Web
Server controls are a compromise between convenience and performance. It is efficient, customizable, and programmable.

8. Use the sqldatareader class for fast data-only cursor

The sqldatareader class provides a method for reading data streams only retrieved from the SQL Server database. If you create an ASP. NET
If you are allowed to use an application, 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, sqldatareader
Class implements the ienumerable interface, which also allows you to bind data to the server control. For more information, see sqldatareader class. Related
For information on how ASP. NET accesses data, see access data through ASP. NET.

9. Use SQL Server Stored Procedures for data access

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.

10. Avoid single-threaded unit (STA) COM components

By default, ASP. NET does not allow any Stas COM component to run on the page. To run them, you must
The aspcompat = true attribute is included in the @ page command. In this way, the thread pool used for execution is switched to the sta thread pool, and the httpcontext
And other built-in objects can be used for COM objects. The former is also a kind of performance optimization, because it avoids any call to mail multi-threaded units (MTA) to the sta thread. Use sta
COM components may greatly damage the performance and should be avoided as much as possible. If you must use the sta COM component, such as in any InterOP
In the scheme, a large number of calls should be made during execution and as much information as possible should be sent during each call. Also, be careful not to create any sta com during page Construction
Component. For example, in the following code, the mystacomponent created by a thread will be instantiated during page construction, and this thread will not run the STA of the page
Thread. This may have a negative impact on performance, because to construct a page, you must complete the sending and receiving process between the MTA and the sta thread.

Dim mycomp as new mystacomponent () Public sub page_load () mycomp. Name = "Bob" End sub

The preferred mechanism is to postpone object creation until the above code is executed in the sta thread in the future, as shown in the following example.

Dim mycomp public sub page_load () mycomp = new mystacomponent () mycomp. Name = "Bob" End sub

We recommend that you construct any COM components and external resources as needed or in the page_load method. Never add any Stas com
Components are stored in shared resources that can be accessed by other threads other than the threads that construct them. Such resources include resources such as cache and session status. Even if the sta thread calls sta com
Component, only the sta com
The component thread can actually call the service for this call, which requires sending the call to the Creator thread. This mail may cause significant performance loss and scalability problems. In this case, please study
The possibility of COM components becoming mta com components, or a better way is to migrate code to make the object a hosted object.

11. migrate call-intensive COM components to managed code

. NET Framework provides a simple method
Components. The advantage is that the new platform can be used while the existing investment is retained. However, in some cases, retaining the performance overhead of the old component makes it worthwhile to migrate the component to the managed code. In every situation
The best way to determine whether to migrate components is to measure the Running Performance of web sites. We recommend that you study how to use any COM that requires a large number of calls for interaction.
Migrate components to managed code. In many cases, it is impossible to migrate legacy components to managed code, especially when the web
Application. 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 large call is not 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
Unicode format. In addition, after processing any COM
Objects or local resources are released. In this way, other requests can use them and minimize the performance problems caused by later requests to the garbage collector to release them.

12. Use early binding in Visual Basic. Net or JScript. Code

In the past, developers liked to use Visual Basic, VBScript. And JScript.
One of the reasons is their so-called "untyped" nature. Variables do not need explicit type declarations and can be created simply by using them. When the data is allocated from one type to another, the conversion is automatically executed.
Line. However, this convenience will greatly damage the performance of the application. Visual Basic now uses Option strict
Compiler commands to support type-safe programming. For backward compatibility, ASP. NET
This option is not enabled. However, to achieve optimal performance, we strongly recommend that you enable this option on the page. To enable option strict, include the strict attribute in @
Page command, or, for user controls, please include this property in @ Control
Command. The following example shows how to set this attribute and calls four variables to show how this attribute causes a compiler error.

JScript.. Net also supports non-type programming, but it does not provide compiler commands that force early binding. If any of the following conditions occurs, the variable is bound late: explicitly declared
An object is a field of a class without a type declaration. It is a special function or method member without an explicit type declaration and cannot deduce the type from its use. The last difference is complicated because if
The jscript. Net compiler can deduce the type based on the usage of the variable and optimize it. In the following example, variable A is bound early, but variable B
Is bound late.

VaR A; var B; A = "hello"; B = "world"; B = 0; to achieve optimal performance, when declaring JScript .. net variable, assign a type to it. For example, var a: string.

13. Make all modules in the request pipeline as efficient as possible

All modules in the request pipeline have the opportunity to be run in each request. Therefore, it is critical to quickly trigger code when a request enters and leaves the module, especially in the code path that does not use the module function. The throughput test is executed when modules and configuration files are used and not used separately, which is very useful for determining the execution speed of these methods.

14. Use httpserverutility. Transfer to redirect between pages of the same application

Use the server. transfer syntax to avoid unnecessary client redirection by using this method on the page.
  
15. Adjust the number of threads for each auxiliary process of the application if necessary

The request structure of ASP. net tries to strike a balance between the number of threads executing the request and the available resources. An application that uses sufficient CPU power is known, and the structure is based on
CPU power to determine the number of requests that can be executed simultaneously. This technology is called thread-control. However, in some conditions, the thread-control algorithm is not very effective. By using ASP. NET
Application Performance object associated with the pipeline instance count performance counter, can be in perfmon
Monitoring thread-control. When a page calls external resources, such as database access or XML Web Services requests, page requests are usually stopped and released
CPU. If a request is waiting for processing and a thread in the thread pool is free, the waiting request will start to be processed. Unfortunately, sometimes this may cause the web
There are a large number of concurrent requests and many waiting threads on the server, which adversely affect the server performance. Generally, if the gate factor is the response time of external resources, too many requests are waiting for resources,
Does not help with the Web server throughput. To alleviate this problem, you can modify
Maxworkerthreads and maxiothreads attributes. manually set the number of threads in the process.

Note: The auxiliary thread is used to process ASP. NET requests, while the IO thread is used to process files, databases, or XML Web Services.
. The value assigned to these attributes is the value of each CPU in the process.
The maximum number of threads of each type. 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. In either case, there are four or eight CPUs
To change the default value. The default value can be used for computers with one or two processors. However, for computers with more processors, one hundred or two hundred threads in a process may cause more disadvantages. Note
If too many threads are involved in the process, the server speed is often reduced. Because of the extra context switch, the operating system spends the CPU cycle on the maintenance thread rather than processing the request.

16. Use the Garbage Collector and Automatic Memory Management of the Common Language Runtime Library as appropriate

Be careful not to allocate too much memory to each request, because the Garbage Collector must do more work more frequently. In addition, do not point unnecessary pointers to objects because they keep objects active,
And try to avoid objects containing the Finalize method, because they will lead to more work later. Especially in finalize
Do not release resources during calls, because resources may always consume memory before being recycled by the garbage collector. At last, this problem often happens to the Web
The performance of the server environment has a devastating impact, because it is easy to exhaust a specific resource while waiting for finalize to run.

17. If there is a large web application, consider executing pre-Batch compilation.

Each time a first request to a directory is sent, a batch compilation is performed. If pages in the directory are not analyzed and compiled, this function analyzes and compiles all pages in the directory in batches to make better use of disks and memory.
If this takes a long time, a single page is quickly analyzed and compiled so that the request can be processed. This function brings ASP. NET
Performance benefit because it compiles many pages into a single assembly. Accessing a page from a loaded assembly is faster than loading a new assembly on each page. The disadvantage of batch compilation is that if the server receives many
For the request of the translated page
When the server analyzes and compiles them, the performance may be poor. To solve this problem, you can execute pre-Batch compilation. Therefore, you only need to request a page from the application before it is activated, regardless of the page. Then, when the user
When you access your site for the first time, the page and its assembly will be compiled. There is no simple mechanism to know when batch compilation will take place. Wait until the CPU is idle or there are no more compiler processes (for example
Start csc.exe (C # compiler) or vbc.exe (Visual Basic compiler. Avoid changing the/bin of the application whenever possible.
Directory. Changing the page will cause re-analysis and compilation of the page, replacing/bin
The Assembly in the directory will cause the directory to be completely re-compiled. On a large site that contains many pages, a better way is to design different directory knots based on the frequency of page replacement or Assembly planned
Structure. Pages that do not often change can be stored in the same directory and pre-compiled at a specific time. Frequently changed pages should be in their own directories (each directory can contain hundreds of pages at most) for quick compilation. Web
Applications can contain many subdirectories. Batch compilation occurs at the directory level, not the application level.

18. Do not rely on exceptions in the code

Exceptions greatly reduce performance, so you should not use them as a way to control normal program processes. If the code may cause exceptions, perform this operation. Do not process this status
Previously caught exceptions themselves. Common solutions include checking for null and assigning it to strings that are analyzed as numeric values.
A value or 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.

Try {result = 100/num;} catch (exception e) {result =
0;} //... to this. If (num! = 0) Result = 100/num; else
Result = 0;

19. Use httpresponse. Write to concatenate strings

This method provides very effective buffering and connection services. However, if you are executing extensive connections, use multiple response. Write calls. The technology shown in the following example is faster than the connection string using a single call to the response. Write method.

Response. Write ("A"); response. Write (mystring); response. Write ("B ");
Response. Write (myobj. tostring (); response. Write ("C ");
Response. Write (mystring2); response. Write ("D"); 20.
Disable the buffer for special reasons.

Disabling web form page buffering can cause a large amount of performance overhead.

21. 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, the view of the server control
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 the server control to the 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. Default
Enable view status for all server controls. To disable view status, set the enableviewstate attribute of the control to false, as shown in the following figure.
The DataGrid Server Control example is shown.

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:

Note: The @ control command also supports enableviewstate.
Attribute, which allows you to control whether the view status is enabled for the user control. To analyze the number of view States used by the server control on the page, (by including the trace = "true" attribute in
@ Page command) Enable the tracing of the page and view the viewstate of the control hierarchy table
Column. For more information about tracing and how to enable it, see ASP. NET tracing.

22. 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 is not recommended in some cases.
Server controls and sending back events. 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
Html
Form Verification user input 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 to store it in the database, you should not write
Code. If you develop custom server controls, consider making them support ecmascript.
Client code. 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. Whether the page is generated in response to the server control event.

Use the page. ispostback attribute to execute code conditionally

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) {// set up a connection
And command here. If (! Page. ispostback) {string query = "select
* From authors where firstname like '% Justin %' "; mycommand. Fill (DS,
"Authors"); mydatagrid. databind ();}}

Since the page_load event is executed during each request, the code above checks whether the ispostback attribute is set
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. Page_load
The Event code 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, it will still be page_load
Event and any server control event on the page are processed.

23. Disable it when the session status is not used

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 session Status of the page, Set
The enablesessionstate attribute in the @ page command is set to false. For example:

Note: If the page needs to access session variables without creating or modifying them, enablesessionstate in the @ page command
Set the attribute to readonly. You can also disable the session Status of the XML Web Services method. For more information, see use ASP. NET and XML
XML Web Services created by the Web Services Client. To disable the application session Status, go to the Application Web. config
In the sessionstate configuration section of the file, set the mode attribute to off. For example:

24. Carefully select the session Status provider

ASP. NET provides three different methods for storing application session data: in-process session Status, out-of-process session status as a Windows service, and SQL
Server
The external session Status in the database. Each method has its own advantages, but the in-process session status is the fastest solution so far. We recommend that you use
In-process providers. Out-of-process solutions are mainly used to scale applications across multiple processors or computers, or to prevent data loss during server or process restart. For more information, see
See ASP. NET status management.

25. 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.

26. ASP. NET application performance test

Before performing a performance test on ASP. NET applications, ensure that the application is correctly functioning and has no errors. The following tools can be used for specific performance tests: Web
Application strees Tool
(Was) is a free test tool released by Microsoft. It can be downloaded from http://webtool.rte.microsoft.com. It can simulate
Hundreds of thousands of users simultaneously make access requests to Web applications, forming a traffic load on the server, so as to achieve the purpose of testing, you can generate average ttfb, average TTLB and other performance summary reports.
Application Center Test (ACT) is a test tool attached to visual
Maxcompute Studio. NET Enterprise Edition is a Web application testing tool officially supported by Microsoft. It can intuitively generate chart results with more functions than was, but does not have multiple customers
The ability to be tested simultaneously. The "performance" counter in the "Administrative Tools" of the server operating system can monitor the server to understand the application performance.

Conclusion:

For website developers, compile ASP. net Applications, develop good habits, improve application performance, at least can delay the necessary hardware upgrade, reduce the cost of the website.

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.