1. Database Access Performance optimization
Connection and shutdown of the database
Accessing a database resource requires creating a connection, opening a connection, and closing a connection several operations. These processes need to exchange information with the database more than once to authenticate and consume server resources. Asp. NET provides a connection pool (Connection pool) to improve the performance impact of opening and shutting down the database. The system places the user's database connection in the connection pool, takes out when needed, recovers the connection when it is closed, and waits for the next connection request.
The size of the connection pool is limited, and if the connection pool is maximized to create a connection, it will have a significant impact on performance. Therefore, after the database connection is established, the connection is opened only when the operation is really needed, closed immediately after use, so as to minimize the time to open the database connection, and avoid the occurrence of exceeding the connection limit.
Using Stored Procedures
A stored procedure is a set of precompiled SQL statements stored on a server, similar to a batch file in a DOS system. The stored procedure has the function of immediate access to the database, and the information processing is very rapid. By using stored procedures, you can avoid multiple compilations of commands, which reside in the cache after a single execution, and need to call only the binary code in the cache at a later time.
In addition, the stored procedure runs on the server side, independent of the ASP.net program, easy to modify, and most importantly, it can reduce the transmission of database operation statements in the network.
Optimizing query Statements
Asp. NET, the ADO connection consumes a large amount of resources, the longer the SQL statement runs, the longer it takes to occupy the system resources. Therefore, try to use optimized SQL statements to reduce execution time. For example, do not include subqueries in query statements, make full use of indexes, and so on.
2. String Operation Performance Optimization
ToString Method with value type
When connecting strings, you often add numbers directly to the string using the "+" number. Although this method is simple, it can get the correct result, but because it involves different data types, the number needs to be converted into a reference type by boxing operation to be added to the string. However, boxing operations have a greater impact on performance because, when such processing is done, a new object is allocated in the managed heap, and the original value is copied to the newly created object.
Use the ToString method of value types to avoid boxing operations, thereby improving application performance.
Using the StringBuilder class
The string class object is immutable, and the method ToString does not significantly improve performance for a string object that is essentially recreating a string object and assigning the new value to the object.
When working with strings, it is best to use the StringBuilder class, whose. NET namespace is system.text. Instead of creating a new object, the class operates directly on the string through methods such as Append,remove,insert, and returns the result of the operation through the ToString method.
Its definition and operation statements are as follows:
int num;
System.Text.StringBuilder str = new System.Text.StringBuilder (); Creating a String
Str. Append (Num. ToString ()); Add Numeric num
Response.Write (str. ToString); Show action Results
3. Optimize the configuration files for your WEB server computer and specific applications to meet your specific needs
By default, the ASP.net configuration is set to enable the broadest range of features and to accommodate the most common scenarios. As a result, application developers can optimize and change some of these configurations to improve application performance, depending on the functionality that the application uses. The following list is some of the options you should consider.
Enable authentication only for the applications that you want. By default, the authentication mode is Windows, or integrated NTLM. In most cases, for applications that require authentication, it is a good idea to disable authentication in the Machine.config file and enable authentication in the Web.config file.
Configure the application according to the appropriate request and response encoding settings. The asp.net default encoding format is UTF-8. If your application is strictly ASCII, configure your application to use ASCII for a slight performance boost.
Consider disabling AutoEventWireup for your application. Setting the AutoEventWireup property to False in the Machine.config file means that the page does not match the method name to the event and hooks the two (for example, Page_Load). If page developers want to use these events, you need to override them in the base class (for example, you need to rewrite page.onload for page load events instead of using the Page_Load method). If AutoEventWireup is disabled, the page gets a slight performance boost 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 features of the For example, if you do not use session state and output caching in your application, you can remove them from the 4. Be sure to disable debug mode
Always remember to disable debug mode before you deploy a production application or perform any performance measurement. If debug mode is enabled, the performance of your application can be significantly affected.
5. For applications that rely extensively on external resources, consider enabling network gardening on multiprocessor computers
The ASP.net process model helps enable scalability on multiprocessor computers, distribute work to multiple processes (one per CPU), and each process sets the processor relationship to its CPU. This technology is called Web gardening. If your application uses a slower database server or calls a COM object with external dependencies (here are just two possibilities), it is useful to enable Web gardening for your application. However, before you decide to enable network gardening, you should test the application's performance in the Web garden.
6. Cache data and page output whenever possible
ASP.net provides simple mechanisms that cache the page output or data when you do not need to dynamically compute page output or data for each page request. In addition, you can optimize the performance of these pages by designing the page and data requests that you want to cache, especially in areas where there is a large amount of traffic expected in the site. Using caching appropriately, compared to any WEB forms functionality of the. NET Framework, can improve the performance of your site, sometimes at a very high order of magnitude.
There are two points to be aware of using the ASP.net caching mechanism. First, do not cache too many items. Caching each item has overhead, especially in terms of memory usage. Do not cache items that are easy to recalculate and rarely use. Second, the expiration of the cached items is not too short. Items that expire quickly can cause unnecessary turnover in the cache and often result in more code cleanup and garbage collection work. If you care about this issue, monitor the Cache total turnover Rate performance counters associated with the ASP.net applications performance object. High turnover may indicate a problem, especially if the item is removed before it expires. This is also called memory pressure.
7. Select the data viewing mechanism for the page or application
Depending on how you choose to display data on a WEB forms page, there is often an important trade-off between convenience and performance. For example, a DataGrid Web server control might be a quick and easy way to display data, but its overhead is often the largest in terms of performance. In some simple cases, you might be able to render data yourself by generating the appropriate HTML, but customization and browser orientation can quickly offset the extra benefits you get. Repeater Web server controls are a trade-off between convenience and performance. It is efficient, customizable and programmable.
8. Use the SqlDataReader class for fast forward-only data cursors
The SqlDataReader class provides a way to read a data-only stream retrieved from a SQL Server database. If you are creating a asp.net application that allows you to use it, the SqlDataReader class provides a higher performance than the DataSet class. This is because SqlDataReader uses SQL Server's native network data transfer format to read data directly from a database connection. In addition, the SqlDataReader class implements the IEnumerable interface, which also allows you to bind data to a server control. For more information, see the SqlDataReader class. For information about how ASP.net accesses data, see Accessing data through asp.net.
9. Use SQL Server stored procedures for data access
In all the data access methods provided by the. NET Framework, SQL Server based data access is a recommended choice for generating high-performance, scalable WEB applications. When you use a managed SQL Server provider, you get additional performance gains by using compiled stored procedures instead of special queries.
10. Avoid single apartment (STA) COM components
By default, ASP.net does not allow any STA COM component to run on the page. To run them, you must include the Aspcompat=true property in the @ Page directive within the. aspx file. This switches the execution thread pool to the STA thread pool and makes HttpContext and other built-in objects available to COM objects. The former is also a performance optimization because it avoids any calls to marshal a multithreaded apartment (MTA) to an STA thread.
Using an STA COM component can significantly impair performance and should be avoided as much as possible. If you must use an STA COM component, such as in any interop scheme, you should make a large number of calls during execution and send as much information as possible during each invocation. 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 is instantiated when the page is constructed, and the thread is not the STA thread that will run the page. This can have a detrimental effect on performance because the marshaling of the MTA and STA threads must be done to construct the page.
<%@ Page language= "VB" aspcompat= "true"%>
<script runat=server>
Dim MyComp as New Mystacomponent ()
Public Sub Page_Load ()
Mycomp.name = "Bob"
End Sub
</script>
<%
Response.Write (Mycomp.sayhello)
%>
The preferred mechanism is to postpone the creation of the object until the above code is executed under 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 ()
Mycomp.name = "Bob"
End Sub
</script>
<%
Response.Write (Mycomp.sayhello)
%>
The recommended practice 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 threads other than the thread that constructs it. Such resources include resources such as caching and session state. Even if an STA thread invokes an STA COM component, only the thread that constructs the STA COM component can actually call the service, which requires marshaling calls to the creator thread. This marshaling can have significant performance loss and scalability issues. In this case, consider 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
The. NET Framework provides an easy way to interact with traditional COM components. The advantage is that the new platform can be used while retaining existing investments. However, in some cases, the performance overhead of retaining legacy components makes it worthwhile to migrate components to managed code. Each situation is different, and the best way to determine whether a component needs to be migrated is to run performance measurements on the WEB site. It is recommended that you examine how to migrate any COM components that require a large number of calls to interact with to managed code.
In many cases, it is not possible to migrate legacy components to managed code, especially when the Web application is originally migrated. In this case, one of the biggest performance hurdles is marshaling data from an unmanaged environment to a managed environment. Therefore, in an interaction operation, perform as many tasks as possible on either end, and then make a large call instead of a series of small calls. For example, all strings in the common language runtime are Unicode, so you should convert all strings in the component to Unicode format before calling managed code.
Also, dispose of any COM object or native resource as soon as you have finished processing it. As a result, other requests can use them and minimize the performance problems caused by 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 liked to use Visual Basic, VBScript, and JScript was their so-called "no type" nature. Variables do not require an explicit type declaration and can be created simply by using them. When an assignment is made from one type to another, the conversion is performed automatically. However, this convenience can greatly impair the performance of the application.
Visual Basic now supports type-safe programming by using the Option Strict compiler directive. For backward compatibility, ASP.net does not enable this option by default. However, for best performance, it is strongly recommended that you enable this option in the page. To enable Option Strict, include the Strict property in the @ Page directive, or, for a user control, include the property in the @ Control directive. The following example shows how to set this property and make four variable calls to show how the property was used to cause a compiler error.
<%@ Page language= "VB" strict= "true"%>
<%
Dim B
Dim C as String
' This'll cause a compiler error.
A = "Hello"
' This'll cause a compiler error.
B = "World"
' This is not cause a compiler error.
C = "!!!!!!"
' But this'll cause a compiler error.
C = 0
%>
JScript. NET also supports no type programming, but it does not provide compiler directives that force early binding. If any of the following conditions occur, the variable is late bound:
is explicitly declared as Object.
is a field of a class that is declared without type.
is a private function or method member without an explicit type declaration, and cannot infer a type from its use.
The final difference is complex, because if the JScript. NET compiler can infer the type based on the use of the variable, it is optimized. In the following example, variable A is early bound, but variable B is late bound.
var A;
var B;
A = "Hello";
B = "World";
B = 0;
For best performance, assign a type to a JScript. NET variable when it is declared. For example, Var a:string.
13. Make all modules within the request pipeline as efficient as possible
All modules within the request pipeline have the opportunity to be run on each request. Therefore, it is critical to quickly trigger code when a request enters and leaves a module, especially in a code path that does not use module functionality. Performing throughput testing, respectively, when using and not using modules and configuration files, is useful for determining how quickly these methods are performed.
14. Redirect between pages of the same application using the HttpServerUtility.Transfer method
Using the Server.Transfer syntax, this method can be used in a page to avoid unnecessary client redirection.
15. Adjust the number of threads per worker process for the application if necessary
The ASP.NET request structure attempts to achieve a balance between the number of threads executing the request and the available resources. An application with sufficient CPU power is known to determine the number of requests that are allowed to execute at the same time, depending on the CPU power available for the request. This technique is called threading gating. However, under some conditions, the thread gate control algorithm is not very effective. You can monitor thread gating in PerfMon by using the Pipeline Instance Count performance counter that is associated with the ASP.net applications performance object.
When a page invokes an external resource, such as database access or an XML Web services request, the page request usually stops and frees the CPU. If a request is waiting to be processed, and a thread in the thread pool is free, the waiting request will begin to be processed. Unfortunately, this can sometimes lead to a large number of simultaneous requests and many waiting threads on the WEB server that adversely affect server performance. Typically, if the gating factor is the response time of an external resource, it is not helpful for the throughput of the WEB server to have too many requests to wait for resources.
To mitigate this situation, you can manually set the number of threads in the process by changing the maxWorkerThreads and Maxiothreads properties of the Machine.config profile <processModel> node.
Note that worker threads are used to handle asp.net requests, while IO threads are used to service data from files, databases, or XML WEB services.
The values assigned to these properties are the maximum number of each type of thread per CPU in the process. For dual-processor computers, the maximum number is twice times the set value. For four-processor computers, the maximum value is four times times the set value. In any case, for computers with four or eight CPUs, it is best to change the default values. For computers with one or two processors, the default value is OK, but for the performance of a computer with more processors, a process with 100 or 200 threads does more harm than good.
Note that too many threads in a process tend to slow down the server because the extra context exchange causes the operating system to spend CPU cycles on maintaining threads rather than processing requests.
16. Proper use of the common language runtime's garbage collector and automatic memory management
Be careful not to allocate too much memory to each request, because the garbage collector will have to do more work more frequently. Also, don't let unnecessary pointers to objects, because they keep the objects active, and you should avoid objects with the Finalize method as much as possible, because they can cause more work later. In particular, you should never release resources in a Finalize call, because resources may consume memory until they are reclaimed by the garbage collector. This last problem often has a devastating impact on the performance of the WEB server environment, as it is easy to deplete a particular resource while waiting for Finalize to run.
17. If you have a large WEB application, consider performing a pre-batch compilation
Batch compilation is performed whenever the first request to the directory occurs. If the pages in the directory are not parsed and compiled, this feature will analyze and compile all pages in the directory in batches to make better use of disk and memory. If this takes a long time, a single page is parsed and compiled quickly so that the request can be processed. This feature brings ASP.net performance benefits because it compiles many pages into a single assembly. Accessing a page from an assembly that is loaded 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 yet been compiled, the performance may be poor when the Web server analyzes and compiles them. To resolve this problem, you can perform a pre-batch compilation. To do this, simply request a page to it before the application is activated, whichever page is available. Then, when the user first accesses your site, the page and its assembly are compiled.
There is no simple mechanism to know when a batch compilation occurs. You need to wait until the CPU is idle or no more compiler processes (such as the csc.exe (C # compiler) or vbc.exe (Visual Basic compiler)) start.
You should also try to avoid changing assemblies in the application's \ Bin directory. Changing the page causes the page to be parsed and compiled, and replacing the assembly in the \ Bin directory causes the catalog to be completely recompiled.
On large-scale sites that contain many pages, a better approach might be to design a different directory structure based on how frequently the page or assembly is planned to be replaced. Pages that are infrequently changed can be stored in the same directory and precompiled at a specific time. Frequently changed pages should be in their own directory (up to hundreds of 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. Do not rely on exceptions in the code
Because exceptions greatly degrade performance, you should not use them as a way to control the normal process flow. Perform this action if it is possible to detect a state in your code that might cause an exception. Do not catch the exception itself before processing the state. Common scenarios include checking for null, assigning a String value that will be parsed as a numeric value, or checking for specific values before applying mathematical operations. The following example shows the code that can cause an exception and the code that tests whether a state exists. Both produce the same result.
Try
{
result = 100/num;
}
catch (Exception e)
{
result = 0;
}
. to this.
if (num!= 0)
result = 100/num;
Else
result = 0;
19. String concatenation using the HttpResponse.Write method
This approach provides a very efficient buffer and connectivity service. However, if you are performing a wide range of connections, use multiple Response.Write calls. The technique shown in the following example is faster than connecting strings with 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. Keep the buffer open unless there are special reasons to turn it off
Disabling buffering of Web forms pages can result in significant performance overhead.
21. Save server control view state only when necessary
Automatic view state management is the function of a server control that enables server controls to repopulate their property values on a round trip (you do not need to write any code). However, because the server control's view state is back and forth from the server in a hidden form field, this feature does have an impact on performance. You should know under what circumstances view state can 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, the saved view state is replaced with the new value obtained from the data-binding operation. In this case, disabling view state can save processing time.
By default, view state is enabled for all server controls. To disable view state, set the control's EnableViewState property to False, as shown in the following DataGrid server control example.
<asp:datagrid enableviewstate= "false" datasource= "..." runat= "Server"/>
You can also use the @ Page directive to disable view state for an entire page. This is useful when you are not sending back to the server from the page:
<%@ Page enableviewstate= "false"%>
Note The EnableViewState property is also supported in the @ Control directive, which allows you to govern whether view state is enabled for a user control.
To analyze the number of view states used by server controls on a page, enable tracing for the page and view the Viewstate columns of the Control hierarchy table (by including the Trace= "true" property in the @ Page directive). For information about tracing and how to enable it, see asp.net tracing.
22. Avoid unnecessary round trips to the server
Although you will most likely want to use the Time-saving and code-saving features of the Web Forms page framework as much as possible, in some cases it is not appropriate to use ASP.net server controls and postback event handling.
Typically, you only need to start a roundtrip process to the server when you retrieve or store data. Most data operations can be performed on the client between these round-trip processes. For example, validating user input from an HTML form can often be done on the client before the data is submitted to the server. In general, if you do not need to pass information to the server to store it in a database, you should not write code that causes a round trip.
If you develop custom server controls, consider having them render client-side code for browsers that support ECMAScript. By using server controls in this way, you can significantly reduce the number of times that information is unnecessarily sent to the WEB server.
Use Page.IsPostBack to avoid unnecessary processing of round trips
If you write code that processes server control postback processing, you may sometimes need to execute other code when the page is first requested, rather than code that executes when the user sends an HTML form that is contained in the page. Conditionally executes code using the Page.IsPostBack property, depending on whether the page is generated in response to a server control event. For example, the following code shows how to create a database connection and a command that binds data to a DataGrid server control when the page is first requested.
void Page_Load (Object sender, EventArgs e)
{
Set up a connection and command.
if (! Page.IsPostBack)
{
String query = "SELECT * from Authors where FirstName like '%justin% '";
Mycommand.fill (ds, "Authors");
Mydatagrid.databind ();
}
}
Because the Page_Load event is executed on each request, the code above checks to see if the IsPostBack property is set to False. If it is, the code is executed. If this property is set to True, the code is not executed.
Note If you do not run this check, the behavior of the postback page will not change. The code for the Page_Load event executes before the server control event is executed, but only the results of the server control event can be rendered on the output page. If you do not run this check, processing will still be performed for the Page_Load event and any server control events on the page.
23. Disable it when session state is not used
Not all applications or pages require session state for specific users, and you should disable session state for any application or page that does not require session state.
To disable the session state of a page, set the EnableSessionState property in the @ Page directive to false. For example, <%@ Page enablesessionstate= "false"%>.
Note If the page requires access to session variables, but does not intend to create or modify them, set the EnableSessionState property in the @ Page directive to ReadOnly.
You can also disable session state for an XML Web services method. For more information, see XML Web Services created using ASP.net and XML Web services clients.
To disable session state for an application, set the Mode property to off in the sessionstate configuration section of the application Web.config file. For example, <sessionstate mode= "off"/>.
24. Carefully select session state provider
ASP.net provides three different methods for storing session data for an 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 method has its own advantages, but in-process session state is by far the fastest solution. If you are storing only a small amount of volatile data in session state, it is recommended that you use an in-process provider. An out-of-process solution is primarily used to scale applications across multiple processors or multiple computers, or for data that cannot be lost when a server or process restarts. For more information, see ASP.net state management.
25. Do not use unnecessary server control
In ASP.net, a large number of server-side controls facilitate program development, but can also result in a loss of performance because each time a user operates a server-side control, a roundtrip process with the server side is generated. Therefore, it is not necessary to use server control sparingly.
-ASP. NET Application Performance test
Before performing a performance test on an asp.net application, make sure that the application is not faulty and that the functionality is correct. Specific performance tests can be performed using the following tools:
WEB Application Strees Tool (WAS) is a free test tool released by Microsoft that can be downloaded from http://webtool.rte.microsoft.com/. It can simulate hundreds of users at the same time access to Web applications requests, the formation of traffic load on the server, so as to achieve the purpose of testing, can generate average TTFB, average TTLB performance summary reports.
Application Center Test (ACT) is a test tool that is attached to the Enterprise Edition of Visual Studio.NET and is a fully supported Web application testing tool for Microsoft. It can visually generate chart results that are more functional than was, but do not have the ability to simultaneously test multiple clients.
The performance counter in the administrative tools of the server operating system to monitor the server to understand application performance.
Conclusion
For Web site developers, when writing asp.net applications, pay attention to performance issues, develop good habits, improve application performance, at least delay the necessary hardware upgrades, reduce the cost of the site.
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.