26 used to optimize the performance of the method in asp.net

1. Database Access Performance Optimization 
 
connection to the database and close

access to the database resources you need to create connections, open the connection and close connection of several operations. These processes require multiple exchange database information to be authenticated, consuming server resources. ASP.NET provides a connection pool (Connection Pool) to improve open and close the impact on database performance. The system users database connection in the connection pool, removed, if desired, retracted closed connection, a connection request waiting time. Connection pool size is limited, if the connection pool to maximize the connection still requires the creation, will greatly affect performance. Therefore, only open after establishing a database connection only when really needed is operatively connected, closed immediately after use, thus minimizing the database connection open time, avoid connection limit exceeded appears.   

Using stored procedures  
 
stored on the server process is a set of pre-compiled SQL statements stored, similar to DOS batch file system. Stored procedure that has immediate access to the database function, an information processing is extremely rapid. Use stored procedures to avoid multiple compilation command, after performing the first of its execution plan resides in the cache, later simply call binary code directly to the cache when needed. Further, stored in the server process running ASP.NET application independent, easy to modify, the most important is that it can reduce transmission in the network database action statement of.

Query optimization
  
ASP.NET, ADO connections consume considerable resources, SQL statement runs longer period of time, taking up system resources longer time. Therefore, to make use of optimized SQL statements to reduce the execution time. For example, the query is not in the sub-query statement includes full use of indexes.   

2. String operation performance optimization 
 
ToString method using the value type
  
When the connection string, often using the "+" sign added directly to a digital string. This method is simple, can be obtained the correct results, but as it relates to a different data type, the desired number of reference type can add to the string by transforming the packing operation. However, a greater impact on the performance of the packing operations, such as during treatment, a new object in the managed heap allocated, to copy the original values of the newly created object. ToString method using the value type of packing operation can be avoided, thereby improving the application performance.   

Use StringBuilder class   

String class object is Bukegaibian, and String objects for re-assignment, in essence, is to re-create a String object and the new value assigned to the object whose method ToString not very significant to improve performance. Through the string, preferably using the StringBuilder class which .NET namespace is System.Text. This class does not create a new object, but to manipulate strings directly through Append, Remove, Insert and other methods, through the ToString method returns the result of the operation. And manipulation statements defined as follows:


int NUM; the System.Text.StringBuilder the System.Text.StringBuilder new new STR = (); // creates a string str.Append (num.ToString ()); // add value num Response .Write (str.ToString); // display the result of the operation 3. optimize Web server configuration files and computer-specific applications to meet your specific needs

by default, ASP.NET configuration is set to enable the most extensive feature and try to adapt to the most common scenario. Therefore, application developers can use the application functionality, optimization and change some of these configurations to improve performance of the application. The following list are some options you should consider.

The application only needs to enable authentication.

By default, the authentication mode is Windows, or integrated NTLM. In most cases, for applications that require authentication, it is best to disable authentication Machine.config file, and enable authentication in the Web.config file. The appropriate application is configured to request and response encoding settings. ASP.NET default encoding format is UTF-8. If your application is strictly ASCII, please configure the application to use ASCII to get a slight performance increase.
  
Consider disabling AutoEventWireup to the application.

In the Machine.config file will AutoEventWireup attribute is set to false, means that the page does not match the method name with the incident and the two hooks (such as Page_Load). If the page developers to use these events need to override these methods in the base class (for example, need to rewrite the page load event Page.OnLoad, instead of using the Page_Load method). If you disable AutoEventWireup, the page will be connected by the events of the left page rather than automatically execute it, get a slight performance boost.

Removable module without a request from the processing pipeline.

By default, all functions Machine.config file server computer nodes are reserved for the activation. According to the function used by the application, you can remove unused modules from the request pipeline to get a slight performance boost. Check each module and its function, according to your need to customize it. For example, if you do not use an output buffer and the session state in the application, they may be removed from the list, to request execution when no other meaningful treatment, not necessary to perform entering and leaving each module of code.

4. Be sure to disable debug mode  

before deploying a production application or any performance measurement, and always remember to disable debug mode. If debug mode is enabled, the application's performance may be a very big impact.   

5. For a wide range of applications that depend on external resources, consider enable network gardening on multiprocessor computers  

ASP.NET process model helps enable scalability on multiprocessor computers will be distributed to more work processes (one for each CPU), and each process will set the processor affinity for CPU. This technique is called Network gardening. If the application uses a slow database server or calls COM objects that have external dependencies (mentioned here only two possibilities), enable network gardening was your application is beneficial. However, before you decide to enable network gardening, you should test the application on the network implementation of the garden.   

6. Whenever possible, the data cache and the page output  

provides a simple mechanism for the ASP.NET, they will not need to cache the page output or data output or data page is calculated dynamically for each page request. Further, the design should be cached pages and data requests (especially in the site traffic is expected to have a greater area), you can optimize the performance of these pages. More than any Web Forms features of the .NET Framework, the proper use of caching can improve site performance better, sometimes orders of magnitude increase is super. Use ASP.NET caching mechanism there are two points to note. First of all, do not cache too many items. Cache for each item are overhead, especially in memory use. Do not cache entry is easy to recalculate and rarely used. Secondly, to the validity of cache entries allocated not too short. Items expire soon lead to unnecessary cache turnover, and often lead to more code cleaning and garbage collection work. If the concern this issue, monitor the ASP.NET Applications performance object associated with the Cache Total Turnover Rate performance counter. High turnover rate may indicate a problem, especially when items are removed prior to maturity. This is also known as memory pressure.


7. Select the appropriate page or application data view mechanism  

Depending on your choice of display data in the Web Forms page mode, in between convenience and performance often there are important trade-offs. For example, DataGrid Web server control may be a convenient way to display data, but the cost in terms of performance it is often the largest. In some simple cases, you by generating the appropriate HTML rendering data yourself can be very effective, but customization and browser orientation will soon be offset by the additional effect obtained. Repeater Web Server Control is a compromise between convenience and performance. It is efficient, customizable and programmable.   

8. The SqlDataReader class for fast-only data cursor  

SqlDataReader class-only provides for reading data streams retrieved from the SQL Server database. The case allows you to use if it appears when you create an ASP.NET application, you SqlDataReader class offers higher performance than the DataSet class. The reason for this situation, because SqlDataReader directly connected to read data from the database using SQL Server's native network data transfer format. In addition, SqlDataReader class implements the IEnumerable interface, which also allows you to bind data to server controls. For more information, please see the SqlDataReader class. How to access information about ASP.NET data, see ASP.NET to access the data through.   

9. The SQL Server stored procedures for data access  

to all data access methods provided in the .NET Framework, SQL Server-based data access is to generate a high-performance, scalable Web applications recommended choice. When using the managed SQL Server provider, you can get an additional performance boost by using compiled stored procedures instead of ad hoc queries.   

10. Avoid single-threaded means (STA) COM Component  

By default, ASP.NET does not allow any STA COM components that run within the page. To run them, must be within the .aspx file ASPCompat = true attribute in the @ Page directive. STA will perform a handover to such a thread pool with a thread pool, but also HttpContext and other objects can be built for a COM object. The former is also a performance optimization, because it avoids the multithreaded unit (MTA) to marshal any calls STA thread. Use STA COM components may greatly damage the performance, should be avoided. If you must use STA COM components, such as in any interop scenario, it should be performed during the execution of a large number of calls and send as much information during each call. Also, be careful not to create any STA COM components during construction page. For example, the following code, when the page structure will be instantiated MySTAComponent created by a thread, and the thread is not STA thread will run the page. This may have an adverse effect on performance, because construction page must complete marshaling between MTA and STA threads.


Dim myComp as new MySTAComponent () Public Sub Page_Load () myComp.Name = "Bob" End Sub


preferred mechanism is to create an object postponed until after executing the code under the STA thread, as shown in the following example.




Dim myComp Public Sub Page_Load () myComp = new MySTAComponent () myComp.Name = "Bob" End Sub

The recommended approach is to construct or any COM components and external resources in the Page_Load method when needed. Sharing resources should never be stored in any STA COM components can be constructed by a thread other than its other threads access to the inside. Such resources include such as caching and session state resources. Even if the STA thread call STA COM component, only the structure of this STA COM component thread can actually call for the service, which requires marshaling the call to the creator thread. This marshaling could have a significant loss of performance and scalability issues. In this case, please look at the possibility of making COM components become MTA COM component, or a better way is to migrate the code to make an object managed object.

 
11. The call-intensive COM components migrate to the managed code  

.NET Framework provides a simple way to interact with traditional COM components. The advantage is that you can take advantage of the new platform while preserving existing investments. However, in some cases, keep the old components performance overhead makes migrating to managed code component is worth it. Each situation is not the same, the best way to decide whether migration component is to run performance measurements on the Web site. I recommend that you look at how to need a lot of calls to any COM components that interact to migrate to managed code. In many cases it is impossible to migrate legacy components to managed code, especially during the initial migration of Web applications. In this case, one of the biggest obstacles to performance data from an unmanaged environment marshaling managed environment. Therefore, interaction, perform as many tasks at either end, and then a big call, rather than a series of smaller calls. For example, the common language runtime all strings are Unicode, it should be before the call managed code components to convert all strings into Unicode format. Further, a processed any COM objects or native resources to release them. Thus, it is possible to use other requests them, and to minimize the performance problems caused by their request later release the garbage collector.   

12. Use early binding in Visual Basic .NET or JScript. Tag  

In the past, developers prefer to use Visual Basic, VBScript. And JScript. One of the reasons is that they are so-called "no type" in nature. Variables do not need explicit type declaration, and can be created simply by using them. When dispensing from one type to another, the conversion is performed automatically. However, this convenience will greatly damage the performance of the application. Visual Basic now supports type-safe programming by using the Option Strict compiler directive. For backward compatibility, by default, ASP.NET does not enable this option. However, in order to get the best performance, it is strongly recommended that you enable this option in the page. To enable Option Strict, please Strict property included in the @ Page directive, or, for user control, the property included in the @ Control directive. The following example shows how to set this property, and the four variables called to show how to use this property causes the compiler error.

JScript. .NET also supports non-type program, but it does not provide mandatory early binding compiler directive. If any of the following occur, the variable is late binding: explicitly declared as Object, a class field untyped is no explicit type declaration of a function or a member of a dedicated method, and its use can not be inferred type. The last difference is more complicated, because if JScript. .NET compiler can infer the type based on usage variables, it will be optimized. In the following example, the variable A is early binding, but the variable B is late binding.

var A; var B; A = "Hello"; B = "World"; B = 0; for optimum performance, the time when the statement JScript .NET variable, assign a type. For example, var A: String.

13. requests that all modules as efficiently as possible in line  

All modules in the request pipeline is run every request has a chance. Therefore, when a request enters and leaves quickly trigger the code module is essential, especially in the code path does not use the module's functions. It is performed when the throughput test modules and with and without profiles, useful for determining the speed of execution of these methods.

14. A method of using HttpServerUtility.Transfer redirection between pages of the same application  

using Server.Transfer syntax, the method used in the page to avoid unnecessary redirects the client.
  
Adjustment of each worker process when an application thread 15. The necessary number of  

requests structure of ASP.NET tries to achieve a balance between available resources and the number of threads of execution. It is known to use a sufficient CPU power application, the structure according to the CPU power available for request, allowing to determine the number of requests executed simultaneously. This technique is known as thread gating. However, under certain conditions, thread gating algorithms are not very effective. Pipeline Instance Count performance counter by using ASP.NET Applications performance associated object, can be monitored in PerfMon thread gating. When the page calls to external resources, such as database access or XML Web services request, the page request generally stops and release the CPU. If a request is waiting to be processed, and there is a thread pool thread is free, then the request that the waiting will begin to be processed. Unfortunately, sometimes this can lead to a number of requests and the large number of simultaneous processing threads are waiting for the presence on the Web server, but they have a negative impact on server performance. In general, if the gating factor is the response time to external resources, then let too many requests waiting for resources, the throughput of the Web server does not help. To mitigate this situation, you can change the Machine.config configuration file node maxWorkerThreads and maxIOThreads attributes, manually set the limit on the number of threads in the process.   

Note: ASP.NET worker thread is used to process the request, and the IO thread is used for the file from the database or XML Web services provide data services, the. The value assigned to these properties are in the process of the maximum number of each type of threads per CPU. For dual processor computer, it is twice the maximum setting value. For four-processor computers, the maximum is four times the set value. In any case, the computer has four or eight CPU, it is best to change the default value. For a computer with one or two processors, the default value can be, but there is more performance computer processors, the process of a hundred or two hundred thread is more harm than good. Note that there are too many threads in the process tends to slow down the server because of the additional context switches will cause the operating system CPU cycles spent on maintenance thread instead of dealing with the request.   

16. The proper use of the common language runtime garbage collector and automatic memory management  

careful not to allocate too much memory to each request, as this garbage collector will have to do more work more often. Also, do not make unnecessary pointer to an object, the object because they will remain active, and should try to avoid objects with Finalize methods because they lead to more work later. Never release resources, especially in the Finalize call, because the resource before it is garbage collected may have been consumed by the memory. This last problem often have Web performance server environments devastating blow, because while waiting for Finalize operation, it is easy to run out of a particular resource.   

17. If you have a large Web application, consider performing pre-batch compilation  

Whenever occurs first request to the directory will execute batch compilation. If the directory pages are not analyzed and compiled, this function will analyze all batch pages and compile directory in order to make better use of disk and memory. If it takes a long time, then quickly analyze and compile a single page, so that the request can be processed. This feature brings the benefits of ASP.NET performance because many pages will be compiled into a single assembly. From the loaded assemblies access to a loading a new page faster than the assembly. Batch compilation disadvantage is that: If the server receives many requests have not yet been compiled pages, then when the Web server and compile their analysis, performance may be poor. To solve this problem, you can perform a pre-batch compilation. To do this, just before the application to activate it requests a page, regardless of which page can be. Then, when the user first visits your site, the page and the assembly will have to be compiled. There is no simple mechanism to know when batch compilation occurs. Need to wait until the CPU is idle or no more compiler processes (eg csc.exe (C # compiler) or vbc.exe (Visual Basic Compiler)) start. You should also try to avoid changing the application assembly bin directory /. Change the page will lead to re-analyze and compile the page, and replace the assembly / bin directory will result in a complete re-compile the batch directory. On the large-scale site contains many pages, a better approach might be based on how often a page or replace the assembly plan to design a different directory structure. Pages that change infrequently can be stored and pre-batch compilation at a specific time in the same directory. Page should change frequently (up to several hundred pages per directory) to quickly compile their own directory. Web applications can contain many subdirectories. Batch compilation occurs at the directory level, not the application level.

18. Do not rely on exceptions in your code  

because the abnormal performance is greatly reduced, so you should not use them as a way to control normal program flow. If it is possible to detect the status code may cause unintentional, perform this operation. Do not catch exceptions before processing the state itself. Common programs include: Check null, will analyze a value assigned to a digital value of String, or check specific values before applying math. The following example shows the code and could lead to an abnormal test whether there is some kind of state of the code. Both produce the same results.


 {Result = 100 the try / NUM;} the catch (Exception E) {Result = 0;} // ... to the this IF Result = 100 / NUM. (NUM = 0!); the else Result = 0;

19. A use HttpResponse .Write string concatenation method is

the method provides a very effective buffer and connection services. However, if you are performing a wide range of connections, use multiple Response.Write calls. Technique shown in the following example is faster than the string with a single call connection 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. unless there are special reasons to close the buffer, otherwise it remains open

to disable Web Forms page buffer can cause a lot of performance overhead.   

21. Save server control view state only when necessary  

Automatic view state management function server control feature 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 view state round trip in a hidden form field on the server, so this function does have an impact on performance. You should know the circumstances under which the state would help view, the circumstances in which it affects the performance pages. For example, if you have the server control binds to data on each round trip, it will operate with the new values from the data obtained by replacing saved view state binding. In this case, the view state is disabled saves processing time. By default, the view state is enabled for all server controls. To disable view state, EnableViewState property of the control is set to false, as in the following example illustrated DataGrid server control.




You can also use the @ Page directive to disable view state of the entire page. When you are not from the page posted back to the server, which will be useful:




Note: @ Control directive also supports EnableViewState property, the directive allows you to control whether view state is enabled for the user control. To view the number of page analysis on the state of server controls use, (by the trace = "true" attribute in the @ Page directive) enabled tracking page and view the Viewstate column Control Hierarchy table. Information about the track and how to enable it, see ASP.NET trace.

22. Avoid unnecessary round trip to the server  

Although you probably want as much as possible to save time and code to use those functions Web Forms page framework, but in some cases but should not use ASP.NET server controls and postback event handling. Usually, only when retrieving or storing data, you only need to start the round trips to the server. Most of the data operation can be performed on the client round-trip between these processes. For example, from an HTML form validation before the client can submit user input to the server at regular data. In general, if you do not pass the information to the server to the database, then you should not write code that leads to and from the stored procedure. If you develop custom server controls, consider them to support ECMAScript. The browser presents the client code. In this way, by using server controls, you can significantly reduce the number sent to the Web server information is unnecessary.

Use Page.IsPostBack avoid performing unnecessary round trip to deal with

the code if you write processing server control postback processing, and sometimes may need to perform additional code when first requested page, rather than when a user sends an HTML window in the page code that executes when the body. According to whether the page is generated in response to a server control events.

Use Page.IsPostBack property to conditionally execute code

example, the following code shows how to create a database connection and command, which is the first time the page is requested to bind data to the DataGrid server control.


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 event is executed every request Page_Load the code checks IsPostBack property is set to false. If yes, then execute the code. If this property is set to true, the code is not executed. Note that if you do not run this check, page postback behavior will not change. Page_Load event in the code before executing the execution server control events, but only the result of a server control events it may appear on the output page. If you do not run this check will be executed for the Page_Load event processing and any server control events on the page.   

23. disable it when not in use session state  

that not all applications or pages are required for session state to a particular user, you should apply to any program or page does not require session state to disable session state. To disable session state pages, EnableSessionState property of the @ Page directive is set to false. For example:



Note: If a page requires access to session variables, but does not intend to create or modify them, EnableSessionState property will be set @ Page directive to ReadOnly. You can also disable session state XML Web services methods. For more information, see Using XML Web services ASP.NET and XML Web services client created. To disable the application's session state, sessionstate configuration section will set the mode attribute in the application Web.config file is off. For example:



24. carefully selected Session State Provider  

ASP.NET provides three different ways to store session data applications: in-process session state out of process as a Windows service session state and SQL Server database process session state. Each method has its own advantages, but in-process session state is by far the fastest solution. If stored in session state only small amounts of volatile data, it is recommended that you use the in-process provider. Out of process solutions are mainly used across multiple processors or multiple computers to scale your application, or loss of data can not be used when a server or process is restarted. For more information, see ASP.NET State Management.   

25. do not use unnecessary Control Server

of ASP.net, a large number of server-side controls to facilitate program development, but could also bring performance loss, because every user operating a server-side controls, it creates a round trip and server-side . Therefore, non-essential, it should be less use Server Control.   

26. ASP.NET application performance testing  

prior to performance testing ASP.NET applications, make sure that the application is not wrong, but function correctly. Specific performance tests can be carried out using the following tools: Web Application Strees Tool (WAS) is a Microsoft released a free testing tool can be downloaded from http://webtool.rte.microsoft.com/. It simulates hundreds of users to simultaneously access a web application request, formed traffic load on the server, so as to achieve the purpose of testing, the TTFB can generate an average, the average TTLB other performance summary reports. Application Center Test (ACT) is a testing tool, incidental to the Enterprise Edition of Visual Studio.NET, Microsoft is officially supported web application testing tool. It can be intuitively generated graph showing the results, more than the WAS function, but do not have the ability to test a plurality of clients simultaneously. Server operating system, "management tool" in the "Performance"   

Conclusion:

For website developers, pay attention to when writing ASP.NET application performance problems, develop good habits, improve application performance, or at least postpone hardware upgrades necessary to reduce the cost of the site.
Published 16 original articles · won praise 1 · views 30000 +

Guess you like

Origin blog.csdn.net/wvtjplh/article/details/4583692