SoFunction
Updated on 2025-03-07

Commonly used methods to optimize performance

1. Database access performance optimization
Database connection and closing
Accessing database resources requires several operations to create a connection, open a connection, and close a connection. These processes require multiple exchanges of information with the database to pass authentication, which is more costly to server resources. Connection Pool is provided in this article to improve the performance impact of opening and closing a database. The system places the user's database connection in the connection pool, takes it out when needed, retrieve the connection when closed, and waits for the next connection request.
The size of the connection pool is limited. If the connection pool is still required to create a connection after it reaches the maximum, it will inevitably greatly affect the performance. Therefore, after establishing a database connection, the connection is only opened when the operation is really needed, and it is closed immediately after use, so as to minimize the time for the database connection to open and avoid situations that exceed the connection limit.
Use stored procedures
A stored procedure is a set of precompiled SQL statements stored on the server, similar to batch files in the DOS system. Stored procedures have the function of instant access to the database and the information is processed extremely quickly. Using stored procedures can avoid multiple compilation of commands. After execution, its execution plan resides in the cache. When needed later, you only need to directly call the binary code in the cache.
In addition, stored procedures run on the server side, independent of the program, and are easy to modify. The most important thing is that they can reduce the transmission of database operation statements on the network.
Optimize query statement
The resources consumed by ADO connections in this paper are quite large, and the longer the SQL statement runs, the longer the system resources will be occupied. Therefore, try to use optimized SQL statements to reduce execution time. For example, do not include subquery statements in the query statement, make full use of indexes, etc.
2. Optimization of string operation performance
ToString method using value type
When concatenating strings, the "+" sign is often used to directly add numbers to the string. Although this method is simple and can also get the correct results, since different data types are involved, numbers need to be converted into reference types through boxing operations before they can be added to the string. However, boxing operations have a great impact on performance, because when performing this type of processing, a new object will be allocated in the managed heap and the original value will be copied to the newly created object.
Using the ToString method of value type can avoid boxing operations, thereby improving application performance.
Use StringBuilder class
String class objects are immutable. Reassigning a String object is essentially recreating a String object and assigning a new value to the object. The performance improvement of ToString is not very significant.
When dealing with strings, it is best to use the StringBuilder class, whose .NET namespace is. This class does not create a new object, but directly operates on the string through Append, Remove, Insert and other methods, and returns the operation result through the ToString method.
The definition and operation statements are as follows:
int num; 
str = new (); //Create a string
(()); //Add numeric num
(); //Show operation results
3. Optimize the configuration files of the web server computer and specific applications to meet your specific needs
By default, the configuration is set to enable the widest range of features and try to adapt to the most common scenarios. Therefore, application developers can optimize and change some of these configurations based on the features used by the application to improve the performance of the application. The following list is some of the options you should consider.
Enable authentication only for the required applications. By default, authentication mode is Windows, or integrated NTLM. In most cases, for applications that require authentication, it is best to disable authentication in the file and enable authentication in the file.
Configure the application according to the appropriate request and response encoding settings. The default encoding format is UTF-8. If your application is strictly ASCII, configure the application to use ASCII for a slight performance improvement.
Consider disabling AutoEventWireup for your application. Setting the AutoEventWireup property to false in the file means that the page does not match the method name to the event and hooks the two (such as Page_Load). If the page developer wants to use these events, they need to override these methods in the base class (for example, they need to override the page load event instead of using the Page_Load method). If AutoEventWireup is disabled, the page will get a slight performance improvement 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 <httpModules> node in the server computer's file are retained as activated. Depending on the functionality used by the application, you can remove unused modules from the request pipeline for a slight performance improvement. Check each module and its features and customize it as you want.
For example, if you do not use session state and output cache in your application, you can remove them from the <httpModules> list so that requests do not have to execute entry and exit code for each module when other meaningful processing is not performed.
4. Be sure to disable debugging mode
Always remember to disable debug mode before deploying production applications or making any performance measurements. If debug mode is enabled, the performance of the application can be greatly affected.
5. For applications that rely widely on external resources, consider enabling network gardening on multiprocessor computers.
The process model helps enable scalability on multiprocessor computers, distributes work to multiple processes (one per CPU) and each process sets the processor relationship to its CPU. This technology is called online gardening. It is beneficial to enable web gardening for your application if the application uses a slower database server or calls a COM object with external dependencies (just mention two possibilities here). However, before deciding to enable web gardening, you should test how your application performs in web gardens.
6. Whenever possible, cache data and page output
Provides some simple mechanisms that cache page output or data when there is no need to request dynamic calculation of page output or data for each page. In addition, the performance of these pages can be optimized by designing cached pages and data requests (especially in areas where there is expected to be a large amount of communication in the site). Compared to any Web form feature of .NET Framework, proper use of caching can better improve site performance, and sometimes this improvement is orders of magnitude.
There are two things to note when using the caching mechanism. First, don't cache too many items. Caching each item has overhead, especially in terms of memory usage. Don't cache items that are easy to recalculate and rarely used. Secondly, the validity period assigned to cached items should not be too short. Items that expire soon lead to unnecessary turnarounds in the cache and often lead to more code removal and garbage collection efforts. If you are concerned about this issue, please monitor the Cache Total Turnover Rate performance counter associated with the Applications performance object. A high turnover rate can indicate a problem, especially if the item is removed before expiration. This is also called memory pressure.
7. Select a data viewing mechanism suitable for the page or application
Depending on how you choose to display data on a web form page, there are often important trade-offs between convenience and performance. For example, DataGrid Web server controls may be a convenient and fast way to display data, but their overhead is often the largest in terms of performance. In some simple cases, it may be effective for you to render your own data by generating the appropriate HTML, but customization and browser orientation can quickly offset the extra benefits you get. Repeater Web server controls are a tradeoff between convenience and performance. It is efficient, customizable and programmable.
8. Use the SqlDataReader class to quickly enter data cursors.
The SqlDataReader class provides a method to read data streams only retrieved from the SQL Server database. If you are allowed to use it when creating an application, the SqlDataReader class provides higher performance than the DataSet class. The reason for this is that SqlDataReader uses SQL Server’s native network data transmission format to read data directly from the database connection. In addition, the SqlDataReader class implements the IEnumerable interface, which also allows you to bind data to server controls. For more information, see the SqlDataReader class. For information on how to access data, see Accessing data through.
9. Use SQL Server stored procedures for data access
Among all data access methods provided by .NET Framework, SQL Server-based data access is the recommended choice for generating high-performance, scalable Web applications. When using a managed SQL Server provider, additional performance improvements can be achieved by using compiled stored procedures instead of special queries.
10. Avoid single-threaded unit (STA) COM components
By default, no STA COM components are allowed to run within the page. To run them, the ASPCompat=true attribute must be included in the @Page directive in the .aspx file. This will switch the thread pool used for execution to the STA thread pool, and make HttpContext and other built-in objects available for COM objects. The former is also a performance optimization because it avoids any calls to marshal multithreaded units (MTAs) to the STA thread.
Using STA COM components may greatly damage performance and should be avoided as much as possible. If you have to use the STA COM component, if in any interop scheme, you should make a large number of calls during execution and send as much information as possible during each call. Also, be careful not to create any STA COM components during the construction of the page. For example, in the following code, the MySTAComponent created by a thread will be instantiated during page construction, and the thread is not the STA thread that will run the page. This may have a negative impact on performance, because to construct the page, marshalling between the MTA and STA threads must be completed.
<%@ Page Language="VB" ASPCompat="true" %> 
<script runat=server> 
Dim myComp as new MySTAComponent() 
Public Sub Page_Load() 
 = "Bob" 
End Sub 
</script> 
<html> 
<% 
() 
%> 
</html> 
The preferred mechanism is to postpone the creation of objects until the above code is executed later in the STA thread, as shown in the following example.
<%@ Page Language="VB" ASPCompat="true" %> 
<script runat=server> 
Dim myComp 
Public Sub Page_Load() 
myComp = new MySTAComponent() 
 = "Bob" 
End Sub 
</script> 
<html> 
<% 
() 
%> 
</html> 
The recommended approach is to construct any COM components and external resources when needed or in the Page_Load method.
Never store any STA COM component in a shared resource that can be accessed by other threads other than the threads that construct it. Such resources include resources like cache and session state. 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 marshaling the calls to the creator thread. This marshaling can cause significant performance losses and scalability issues. In this case, look into the possibility of making a COM component an MTA COM component, or better yet, migrate the code to make the object a managed object.
11. Migrate call-intensive COM components to managed code
.NET Framework provides an easy way to interact with traditional COM components. The advantage is that it can leverage new platforms while retaining existing investments. But in some cases, the performance overhead of retaining old components makes it worthwhile to migrate components to managed code. Each situation is different, and the best way to decide whether components need to be migrated is to measure the performance of the Web site. It is recommended that you look at how to migrate any COM component that requires a lot of calls to interact with to managed code.
It is impossible to migrate legacy components to managed code in many cases, especially when initially migrating a web application. In this case, one of the biggest performance hurdles is marshaling data from an unmanaged environment to a managed environment. So, in an interaction, do as many tasks as possible on either end and make a big call instead of a series of small calls. For example, all strings in the common language runtime are Unicode, so all strings in the component should be converted into Unicode format before calling managed code.
In addition, release any COM objects or native resources as soon as they are processed. This way, other requests can use them and minimize performance issues arising from requesting the garbage collector to release them later.
12. Use early binding in Visual Basic .NET or JScript code
In the past, one of the reasons developers like to use Visual Basic, VBScript, and JScript was their so-called "typeless" nature. Variables do not require explicit type declarations and can be created simply by using them. When allocating from one type to another, the conversion is performed automatically. However, this convenience can greatly damage the performance of the application.
Visual Basic now supports type-safe programming by using the Option Strict compiler directive. For backward compatibility, this option is not enabled by default. However, for optimal performance, it is highly recommended to enable this option in the page. To enable Option Strict, include the Strict property in the @ Page directive, or, for user controls, include the property in the @ Control directive. The following example demonstrates how to set the property and makes four variable calls to show how using the property causes compiler errors.
<%@ 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 typeless programming, but it does not provide compiler instructions that force early binding. If any of the following happens, the variable is late bound:
It is explicitly declared as Object.
Is a field of a class without type declaration.
is a dedicated function or method member without an explicit type declaration and cannot infer the type from its use.
The last difference is more complicated because if the JScript.NET compiler can infer the type based on the usage of the variable, it will optimize. 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; 

For best performance, when declaring a JScript .NET variable, assign it a type. For example, var A : String.
13. Make all modules in the request pipeline as efficient as possible.
All modules within the request pipeline have a chance to be run in each request. Therefore, it is crucial to quickly trigger the code when requests enter and leave the module, especially in code paths that do not use module functions. Performing throughput tests when using and without modules and configuration files is useful for determining the execution speed of these methods.
14. Use the method to redirect between pages of the same application
Using the syntax, using this method in the page can avoid unnecessary client redirects.
15. Adjust the number of threads per worker process of the application if necessary
The request structure attempts to achieve a balance between the number of threads that execute the request and the available resources. An application that uses enough CPU power is known, and this structure will determine the number of requests allowed to be executed simultaneously based on the CPU power available for requests. This technology is called thread gate. However, under certain conditions, the thread gate algorithm is not very effective. Thread gating can be monitored in PerfMon by using the Pipeline Instance Count performance counter associated with the Applications performance object.
When a page calls external resources, such as a database access or XML Web services request, the page request usually stops and frees the CPU. If a request is waiting to be processed and there is a thread in the thread pool that is free, the waiting request will begin to be processed. Unfortunately, sometimes this can lead to a large number of simultaneous processing requests and many waiting threads on the web server, which have a negative impact on server performance. Generally, if the gating factor is the response time of an external resource, letting too many requests wait for the resource will not help the throughput of the Web server.
To alleviate this situation, you can manually set the number of threads in the process by changing the maxWorkerThreads and maxIOThreads properties of the node of the configuration file <processModel>.
Note that the secondary thread is used to process requests, while the IO thread is used to provide services for data from files, databases, or XML Web services.
The value assigned to these properties is the maximum number of threads per class in the process for each CPU. For dual-processor computers, the maximum number is twice the set value. For a quad-processor computer, the maximum value is four times the set value. In any case, for computers with four or eight CPUs, it is best to change the default value. For computers with one or two processors, the default value is OK, but for computers with more processors, having one hundred or two hundred threads in a process will do more harm than good.
Note that too many threads in the process tend to slow down the server because the additional context switch causes the operating system to spend CPU cycles on maintaining threads rather than processing requests.
16. Garbage collector and automatic memory management that appropriately use the common language runtime library
Be careful not to allocate too much memory to each request, as this way the garbage collector will have to do more work more frequently. Also, don't let unnecessary pointers point to objects, as they will keep the object active, and objects with Finalize methods should be avoided as they will cause more work later. Especially in Finalize calls, never release resources, because resources may consume memory before being recycled by the garbage collector. This last problem often has a devastating blow to the performance of the Web server environment, because it is easy to exhaust a specific resource while waiting for Finalize to run.
17. If there is a large web application, you can consider performing pre-compilation
Batch compilation is performed whenever the first request to the directory occurs. If the pages in the directory are not analyzed and compiled, this feature analyzes and compiles all pages in the directory in batches to better utilize disk and memory. If this takes a long time, a single page will be quickly analyzed and compiled so that the request can be processed. This feature brings performance benefits because it compiles many pages into a single assembly. Accessing a page from a loaded assembly is faster than loading a new assembly per page.
The disadvantage of batch compilation is that if the server receives many requests for pages that have not been compiled, then performance may be poor when the web server analyzes and compiles them. To solve this problem, pre-package compilation can be performed. To do this, just request a page from the application before it is activated, no matter which page you want. Then, when the user first accesses your site, the page and its assembly will be compiled.
There is no simple mechanism to know when batch compilation occurs. You need to wait until the CPU is idle or there are no more compiler processes (such as (C# compiler) or (Visual Basic compiler)) start.
You should also try to avoid changing the assembly in the application's \bin directory. Changing the page will cause the page to be re-analyzed and compiled, while replacing the assembly in the \bin directory will cause the directory to be completely re-batched.
On large-scale sites that contain many pages, a better approach might be to design different directory structures based on how frequently a page or assembly is planned to be replaced. Pages that are not frequently changed can be stored in the same directory and pre-compiled at a specific time. Pages that change frequently should be in their own directories (up to a few hundred pages per directory) for quick compilation.
Web applications can contain many subdirectories. Batch compilation occurs at the directory level, not at the application level.
18. Don't rely on exceptions in the code
Because exceptions greatly reduce performance, you should not use them as a way to control normal program flow. Do this if it is possible to detect a state in the code that may cause an exception. Do not catch the exception itself before processing the state. Common solutions include: checking null, assigning a value to String that will be analyzed as a numeric value, or checking a specific value before applying mathematical operations. The following example demonstrates code that may cause an exception and code that tests whether there is a certain state. Both produce 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 the method to conduct string concatenation
This method provides very efficient buffering and connection services. However, if you are executing extensive connections, use multiple calls. The technique shown in the example below is faster than connecting strings with a single call to the method.
("a"); 
(myString); 
("b"); 
(()); 
("c"); 
(myString2); 
("d"); 
20. Keep the buffer on unless there is a special reason.
Disabling the buffering of Web form pages will lead to a lot of performance overhead.
21. Only save the server control view status if necessary
Automatic view state management is a feature of server controls that enable server controls to refill their property values ​​on the round trip process (you don't need to write any code). However, because the view state of the server control goes back and forth to the server in a hidden form field, this feature does have a performance impact. You should know in which situations the view state will help and in which cases it affects the performance of the page. For example, if you bind a server control to data on each round trip process, the saved view state will be replaced with the new value obtained from the data binding operation. In this case, disabling the view state can save processing time.
By default, view state is enabled for all server controls. To disable view state, set the EnableViewState property of the control to false, as shown in the DataGrid server control example below.
<asp:datagrid EnableViewState="false" datasource="..." runat="server"/> 
You can also use the @Page directive to disable the view state of the entire page. This is useful when you do not post back from the page to the server:
<%@ Page EnableViewState="false" %> 
Note that the EnableViewState property is also supported in the @Control directive, which allows you to control whether view state is enabled for user controls.
To analyze the number of view states used by server controls on a page, enable tracking of the page and view the Viewstate column of the Control Hierarchy table. For information on tracking and how to enable it, see Tracking.
22. Avoid unnecessary round trip process to the server
While you may very likely want to use as much time-saving and code-saving features of the Web Form Page Framework, in some cases it is not advisable to use server controls and postback event handling.
Usually, you only need to start the round trip process to the server when you retrieve or store data. Most data operations can be performed on clients between these round trips. For example, validating user input from HTML forms can often be done on the client before data is submitted to the server. In general, if you don't need to pass information to the server to store it in the database, you shouldn't write code that causes a round trip process.
If you are developing custom server controls, consider having them render client code for ECMAScript-enabled browsers. By using server controls in this way, you can significantly reduce the number of times the information is sent to the Web server unnecessarily.
Use  Avoid unnecessary processing of the round trip process
If you write code that handles server control postback processing, you may sometimes need to execute other code when the page is first requested, rather than when the user sends the HTML form included in the page. Depending on whether the page was generated in response to server control events, use the attribute to execute the code conditionally. For example, the following code demonstrates how to create a database connection and command that binds data to the DataGrid server control when the page is first requested.
void Page_Load(Object sender, EventArgs e) 

// Set up a connection and command here. 
if (!) 

String query = "select * from Authors where FirstName like '%JUSTIN%'"; 
(ds, "Authors"); 
(); 



Since the Page_Load event is executed every time the request is requested, the above code checks whether the IsPostBack property is set to false. If so, execute the code. If the property is set to true, the code is not executed.
Note If this check is not run, the behavior of postback pages will not change. The code of the Page_Load event is executed before the server control event is executed, but only the result of the server control event can be rendered on the output page. If the check is not run, processing will still be performed for the Page_Load event and any server control events on that page.
23. Disable it when the session state is not used
Not all applications or pages need to be user-specific session state, and you should disable session state for any application or page that does not require session state.
To disable the session state of the page, set the EnableSessionState property in the @Page directive to false. For example, <%@ Page EnableSessionState="false" %>.
Note: If the page needs to access session variables but does not intend to create or modify them, set the EnableSessionState property in the @Page directive to ReadOnly.
The session state of the XML Web services method can also be disabled. For more information, see XML Web services created using the XML Web services client.
To disable the session state of the application, set the mode property to off in the sessionstate configuration section of the application file. For example, <sessionstate mode="off" />.
24. Carefully select the session status provider
There are three different methods for storing the session data of the application: in-process session state, out-of-process session state as a Windows service, and out-of-process session state in the SQL Server database. Each approach has its own advantages, but in-process session state is by far the fastest solution. If you only store a small amount of volatile data in session state, you are recommended to use an in-process provider. Off-process solutions are primarily used to scale applications across multiple processors or multiple computers, or to situations where data cannot be lost when a server or process restarts. For more information, see Status Management.
25. Don’t use unnecessary Server Control
In this case, a large number of server-side controls facilitate program development, but may also bring performance losses, because every time a user operates the server-side control, a round-trip process with the server-side is generated. Therefore, Server Control should be used less unless necessary.
26. Application performance testing
Before performing performance testing on your application, make sure that the application is error-free and that it is functionally correct. Specific performance testing can be carried out using the following tools:
Web Application Strees Tool (WAS) is a free testing tool released by Microsoft that can be downloaded from/. It can simulate hundreds or thousands of users to make access requests to web applications at the same time, forming traffic load on the server, thereby achieving the purpose of testing, and generating performance summary reports such as average TTFB and average TTLB.
Application Center Test (ACT) is a testing tool that comes with the Enterprise Edition of Visual 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 test multiple clients simultaneously.
The Performance counter in the Server Operating System "Management Tools" can monitor the server to understand application performance.
in conclusion
For website developers, paying attention to performance issues when writing applications, developing good habits, improving application performance, and at least postpone the necessary hardware upgrades and reduce the cost of the website.