26 common methods to optimize ASP. NET performance

Source: Internet
Author: User
Tags add numbers
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. 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.

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. The stored procedure 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 in the cache when necessary.CodeYou can. In addition, the stored procedure runs on the server and is independent of ASP. NET.ProgramTo facilitate 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. 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.

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, 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. Optimize configuration files for Web 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 best to disable authentication in the machine. config file and enable authentication in the web. config file for applications that require authentication. Configure the application based on the appropriate request and response encoding settings. ASP. NET default encoding format is UTF-8. If your application is strictly ASCII, configure the application to use ASCII for a slight performance improvement.

Disable autoeventwireup for applications.

In the machine. config file, set the autoeventwireup attribute to false, which means that the page does not match the method name with the 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 rewrite page. onload for page loading events, rather than using the page_load method ). If autoeventwireup is disabled, the page will be slightly improved by leaving the event connection to the page author rather than automatically executing it.

Remove unused modules from the request processing pipeline.

By default, all functions of nodes in the machine. config file of the server computer are retained to 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 list so that requests do not perform other meaningful processing, you do not have to execute the code for entering and leaving each module.

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, distribute work to multiple processes (one CPU per worker), and each process sets the processor relationship to its 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, you should test how applications are executed in the Web garden.

 

3. Optimize configuration files for Web 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 best to disable authentication in the machine. config file and enable authentication in the web. config file for applications that require authentication. Configure the application based on the appropriate request and response encoding settings. ASP. NET default encoding format is UTF-8. If your application is strictly ASCII, configure the application to use ASCII for a slight performance improvement.

Disable autoeventwireup for applications.

In the machine. config file, set the autoeventwireup attribute to false, which means that the page does not match the method name with the 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 rewrite page. onload for page loading events, rather than using the page_load method ). If autoeventwireup is disabled, the page will be slightly improved by leaving the event connection to the page author rather than automatically executing it.

Remove unused modules from the request processing pipeline.

By default, all functions of nodes in the machine. config file of the server computer are retained to 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 list so that requests do not perform other meaningful processing, you do not have to execute the code for entering and leaving each module.

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, distribute work to multiple processes (one CPU per worker), and each process sets the processor relationship to its 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, you should test how applications are executed in the Web garden.

 

 

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.

<% @ Page Language = "VB" aspcompat = "true" %>
<Script. runat = Server>
Dim mycomp
Public sub page_load ()
Mycomp = new mystacomponent ()
Mycomp. Name = "Bob"
End sub
</SCRIPT>
<HTML>
<%
Response. Write (mycomp. sayhello)
%>
</Html>

We recommend that you construct any COM components and external resources as needed or in the page_load method. Never store any Stas COM component in shared resources that can be accessed by other threads other than the threads that construct it. Such resources include resources such as cache and session status. Even if the sta thread calls the sta COM component, only the thread that constructs the sta COM component can actually serve the call, which requires sending and processing calls to the Creator thread. This mail may cause significant performance loss and scalability problems. In this case, consider the possibility of making the COM component an mta com component, or migrate code to make the object a hosted object.

11. migrate call-intensive COM components to managed code

. NET Framework provides a simple way to interact with traditional COM 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. Every situation is different. 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 migrate any COM component that requires a large number of calls for interaction 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 make a large 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. In addition, after processing any COM objects or local resources, 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.

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

In the past, one of the reasons why developers like to use Visual Basic, VBScript, and JScript is the so-called "non-type" 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. However, this convenience will greatly damage the performance of the application. Visual Basic now supports type-safe programming by using the option strict compiler command. For backward compatibility, ASP. NET does not enable this option by default. 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 the @ page command, or include this attribute in the @ control command for user controls. The following example shows how to set this attribute and calls four variables to show how this attribute causes a compiler error.

<% @ Page Language = "VB" strict = "true" %>
<%
Dim B
Dim C as string
'This will cause a compiler error.
A = "hello"
'This will cause a compiler error.
B = "world"
'This will not cause a compiler error.
C = "!!!!!! "
'But this will cause a compiler error.
C = 0
%>

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 in the late stage: it is explicitly declared as an object and is a field of the class without type declaration, is a special function or method member without 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, it will be optimized. In the following example, variable A is bound early, but variable B is bound late.

VaR;

VaR B;

A = "hello ";

B = "world ";

B = 0;

To achieve optimal performance, assign a type to the JScript.. Net variable when declaring 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. 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 conditionsAlgorithmNot very effective. By using the pipeline instance count performance counter associated with the performance object of ASP. NET applications, You can monitor thread-control in perfmon. When a page calls external resources, such as database access or XML Web Services requests, the page requests usually stop and release the 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 lead to a large number of concurrent requests and many waiting threads on the Web server, which have adverse effects on server performance. Generally, if the gate factor is the response time of external resources, too many requests are waiting for resources, which is not helpful for the Web server throughput. To alleviate this problem, you can manually set the number of threads in the process by changing the maxworkerthreads and maxiothreads attributes of the machine. config configuration file node.

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 these attributes is the maximum number of threads in 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. In any case, it is best to change the default value for computers with four or eight CPUs. 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 that too many threads in the process will often reduce the server speed, because the operating system will spend the CPU cycle on the maintenance thread rather than processing the request due to extra context switching.

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 in the late stage: it is explicitly declared as an object and is a field of the class without type declaration, is a special function or method member without 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, it will be optimized. In the following example, variable A is bound early, but variable B is bound late.

VaR;

VaR B;

A = "hello ";

B = "world ";

B = 0;

To achieve optimal performance, assign a type to the JScript.. Net variable when declaring 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. 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. However, in some conditions, the thread-control algorithm is not very effective. By using the pipeline instance count performance counter associated with the performance object of ASP. NET applications, You can monitor thread-control in perfmon. When a page calls external resources, such as database access or XML Web Services requests, the page requests usually stop and release the 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 lead to a large number of concurrent requests and many waiting threads on the Web server, which have adverse effects on server performance. Generally, if the gate factor is the response time of external resources, too many requests are waiting for resources, which is not helpful for the Web server throughput. To alleviate this problem, you can manually set the number of threads in the process by changing the maxworkerthreads and maxiothreads attributes of the machine. config configuration file node.

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 these attributes is the maximum number of threads in 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. In any case, it is best to change the default value for computers with four or eight CPUs. 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 that too many threads in the process will often reduce the server speed, because the operating system will spend the CPU cycle on the maintenance thread rather than processing the request due to extra context switching.

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 in the late stage: it is explicitly declared as an object and is a field of the class without type declaration, is a special function or method member without 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, it will be optimized. In the following example, variable A is bound early, but variable B is bound late.

VaR;

VaR B;

A = "hello ";

B = "world ";

B = 0;

To achieve optimal performance, assign a type to the JScript.. Net variable when declaring 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. 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. However, in some conditions, the thread-control algorithm is not very effective. By using the pipeline instance count performance counter associated with the performance object of ASP. NET applications, You can monitor thread-control in perfmon. When a page calls external resources, such as database access or XML Web Services requests, the page requests usually stop and release the 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 lead to a large number of concurrent requests and many waiting threads on the Web server, which have adverse effects on server performance. Generally, if the gate factor is the response time of external resources, too many requests are waiting for resources, which is not helpful for the Web server throughput. To alleviate this problem, you can manually set the number of threads in the process by changing the maxworkerthreads and maxiothreads attributes of the machine. config configuration file node.

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 these attributes is the maximum number of threads in 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. In any case, it is best to change the default value for computers with four or eight CPUs. 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 that too many threads in the process will often reduce the server speed, because the operating system will spend the CPU cycle on the maintenance thread rather than processing the request due to extra context switching.

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

<% @ Page enablesessi %>

Note: If the page needs to access session variables without creating or modifying 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 clients. 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. For example:

<Sessionstate mode = "off"/>

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 out-of-process session Status in the SQL Server database. 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. 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 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. You can use the following tools to test the performance: 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 to access web applications, form a traffic load on the server, so as to achieve the purpose of testing, can generate average ttfb, average TTLB and other performance summary reports. Application Center Test (ACT) is a testing tool that is attached to the Enterprise Edition of Visual Studio. NET and 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 the ability to be tested simultaneously by multiple clients. 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. net Applications, develop good habits, improve application performance, at least can delay the necessary hardware upgrade, reduce the cost of the website.

Related Article

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.