Asp. The methods used to optimize performance in net

Source: Internet
Author: User
Tags add numbers connection pooling html form

1. Database Access Performance Optimization

Connection and shutdown of the database

Accessing a database resource requires creating a connection, opening a connection, and closing the connection several operations. These processes need to exchange information with the database multiple times to pass authentication, which consumes server resources more often. Asp. NET provides connection pooling (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, reclaims the connection when it closes, and waits for the next connection request.

The size of the connection pool is limited, and if you still need to create a connection when the connection pool reaches the maximum, you will inevitably have a significant impact on performance. Therefore, after establishing a database connection only when the actual need to open the connection, the use is closed immediately, so as to minimize the database connection open time, to avoid the situation beyond the connection limit.

Using Stored Procedures

A stored procedure is a set of precompiled SQL statements stored on the server, similar to a batch file in a DOS system. Stored procedures have immediate access to the database and information processing is extremely rapid. You can use stored procedures to avoid multiple compilations of commands, and after execution, their execution plans reside in the cache, and you need to call the binary code in the cache directly later.

In addition, stored procedures run on the server side, independent of the ASP. NET program, easy to modify, most importantly, it can reduce the database operation statements in the network transmission.

2. String Manipulation Performance Optimization

Use the ToString method of a value type

When you connect strings, you often use the "+" sign to add numbers directly to a string. This method, while simple, can get the correct results, but because of the different data types involved, the numbers need to be converted to reference types by boxing to be added to the string. However, boxing operations have a large impact on performance because, when such processing occurs, a new object is assigned to the managed heap and the original value is copied to the newly created object.

Use the ToString method of a value type to avoid boxing operations, which can improve application performance.

Using the StringBuilder class

The string class object is immutable, and the re-assignment of a string object is essentially a re-creation of a string object and assigning the new value to the object, and its method of ToString does not significantly improve performance.

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 directly operates on the string using methods such as Append,remove,insert and returns the result of the operation through the ToString method.

The definitions and operation statements are as follows:

int num;
System.Text.StringBuilder str = new System.Text.StringBuilder (); Create a string
Tr. Append (Num. ToString ()); Add Value num
Response.Write (str. ToString); Show Operation results

Refine query statements

Asp. NET ADO connections consume a considerable amount of resources, the longer the SQL statement runs, the longer it takes to take up system resources. Therefore, use optimized SQL statements as much as possible to reduce execution time. For example, do not include subqueries in query statements, make full use of indexes, and so on.

3. Optimize the configuration files for your WEB server computers and specific applications to meet your specific needs

By default, the ASP. NET configuration is set to enable the widest range of features and is as adaptable as possible to the most common scenarios. As a result, application developers can optimize and change some of these configurations to improve application performance based on the functionality used by the application. The following list is some of the options you should consider.

Enable authentication only for the applications that you need. 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 the application to use ASCII for a little performance improvement.

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, they need to override them in the base class (for example, you need to override page.onload for a page load event 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 automating it.

Removes 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 measurements. If debug mode is enabled, the performance of the application can be very much affected.

5. For applications that rely extensively on external resources, consider enabling Web gardening on a multiprocessor computer

The ASP. NET process model helps enable scalability on multiprocessor computers, distributing work to multiple processes (one per CPU), and each process sets the processor relationship to its CPU. This technique is called Web gardening. If your application uses a slower database server or calls a COM object with external dependencies (only two possibilities are mentioned here), it is beneficial to enable Web gardening for your application. However, before you decide to enable Web gardening, you should test the application's performance in the network garden.

6. Cache data and page output whenever possible

ASP. NET provides a few simple mechanisms for caching page output or data when you do not need to dynamically calculate page output or data for each page request. In addition, you can optimize the performance of these pages by designing the pages and data requests that you want to cache, especially in areas where you expect to have a large amount of traffic in your site. Using caching appropriately compared to any Web forms feature of the. NET Framework can better improve the performance of your site, sometimes at an extra-order level.

There are two points to be aware of using the ASP. First, do not cache too many items. There is a cost to caching each item, especially in terms of memory usage. Do not cache items that are easy to recalculate and seldom used. Second, assign the cached item an expiration date that is not too short. Items that expire soon cause unnecessary turnover in the cache and often lead to more code cleanup and garbage collection work. If you are concerned about this issue, monitor the Cache total turnover rate performance counter associated with the ASP. NET Applications performance object. A high turnover rate may indicate a problem, especially when an item is removed before it expires. This is also known as memory pressure.

7. Select the data viewing mechanism that is appropriate for the page or application

There are often important tradeoffs between convenience and performance, depending on how you choose to display the data on a Web forms page. For example, a DataGrid Web server control might be a quick and easy way to display data, but it is often the most expensive in terms of performance. In some simple cases, it may be useful to render your data yourself by generating the appropriate HTML, but customization and browser orientation will 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. Using the SqlDataReader class for fast forward-only data cursors


The SqlDataReader class provides a way to read a forward-only stream of data retrieved from a SQL Server database. The SqlDataReader class provides higher performance than the DataSet class if you are allowed to use it when you create an ASP. This is the case because SqlDataReader uses SQL Server's native network data transfer 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 about how ASP. NET accesses data, see Accessing Data through ASP.

9. Using SQL Server stored procedures for data access

In all of the data access methods provided by the. NET Framework, SQL Server-based data access is the recommended choice for building high-performance, scalable WEB applications. When you use a managed SQL Server provider, you gain additional performance gains by using compiled stored procedures instead of special queries.

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

By default, ASP. NET does not allow any STA COM components to run inside the page. To run them, you must include the Aspcompat=true property within the. aspx file in the @ Page directive. 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 the multithreaded Unit (MTA) to the STA thread.

Using STA COM components can greatly impair performance and should be avoided as much as possible. If you must use an STA COM component, such as in any interop scenario, 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 adversely affect performance because the marshaling between the MTA and STA threads must be completed to construct the page.

Lt;script runat=server>
Dim MyComp as New Mystacomponent ()
Public Sub Page_Load ()
Mycomp.name = "Bob"
End Sub
Lt;/script>
Lt;html>
lt;%
Response.Write (Mycomp.sayhello)
%>
Lt;/html>

The preferred mechanism is to defer the creation of the object until the preceding code is executed under the STA thread, as shown in the following example.

lt;%@ page language= "VB" aspcompat= "true"%>
Lt;script runat=server>
Dim MyComp
Public Sub Page_Load ()
MyComp = new Mystacomponent ()
Mycomp.name = "Bob"
End Sub
Lt;/script>
Lt;html>
lt;%
Response.Write (Mycomp.sayhello)
%>
Lt;/html>

It is recommended to construct any COM components and external resources when needed or in the Page_Load method.
Never store any STA COM components in a shared resource that can be accessed by a thread other than the thread that constructs it. Such resources include resources such as 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, and this requires marshaling the call to the creator thread. This marshaling can have significant performance loss and scalability issues. In this case, consider the possibility of making COM components an MTA COM component, or a better way to migrate the code to make the object a managed object.

11. Migrating Call-intensive COM components to managed code

The. NET Framework provides an easy way to interact with traditional COM components. The advantage is that you can take advantage of the new platform while preserving your existing investments. However, in some cases, preserving the performance overhead of legacy components makes it worthwhile to migrate components to managed code. Each situation is different, and the best way to decide whether to migrate components is to run performance measurements on the WEB site. It is recommended that you explore how to migrate any COM components that require a large number of calls for interaction to managed code.

In many cases, it is not possible to migrate legacy components to managed code, especially when the Web application was 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 interactive operation, perform as many tasks as possible at 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 the strings in the component to Unicode format before calling managed code.

Also, dispose of any COM objects or native resources before disposing of them. This allows other requests to use them and minimizes performance issues caused by later requests to the garbage collector to release them.

12. Using early binding in Visual Basic. NET or JScript code

In the past, one of the reasons developers prefer to use Visual Basic, VBScript, and JScript is their so-called "untyped" nature. Variables do not require explicit type declarations and can be easily created by using them. When you assign from one type to another, the transformation is performed automatically. However, this convenience can greatly impair the performance of your application.

Visual Basic now supports type-safe programming by using the Option Strict compiler directive. For backward compatibility, the option is not enabled by default for ASP. 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 the property and makes four variable calls to show how the use of the property causes a compiler error.

lt;%
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 would cause a compiler error.
C = 0
%>

JScript. NET also supports untyped 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 an Object.
is a field of a class that has no type declaration.
is a private function or method member that does not have an explicit type declaration, and cannot infer the type from its use.
The last difference is complicated, because if the JScript. NET compiler can infer the type based on the usage of the variable, it will be optimized. In the following example, the variable A is early bound, but the 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 you declare it. For example, Var a:string.

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

All modules within the request pipeline have an opportunity to be run in each request. Therefore, it is critical to quickly trigger code when requests enter and leave the module, especially in code paths that do not use module functionality. Performing throughput tests, respectively, when using and not using modules and configuration files, is useful for determining how quickly these methods are performed.

14. Use the HttpServerUtility.Transfer method to redirect between pages in the same application

Using the Server.Transfer syntax, use this method on the page to avoid unnecessary client redirection.

15. Adjust the number of threads per worker process for your application if necessary

The request structure of ASP. NET attempts to achieve a balance between the number of threads executing the request and the available resources. An application that uses enough CPU power is known to determine the number of simultaneous requests that are allowed based on the CPU power available to the request. This technique is called thread gating. However, under certain conditions, the thread gating algorithm is not very effective. Thread gating can be monitored in PerfMon by using the Pipeline Instance Count performance counter associated with the ASP. Applications performance object.

When a page calls an external resource, such as a database access or an XML Web services request, the page request typically 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 to have too many requests waiting for the resource for the WEB server's throughput.

To mitigate this, you can manually set the limit on the number of threads in the process by changing the maxWorkerThreads and Maxiothreads properties of the Machine.config configuration file node.

Note: Worker threads are used to process ASP., 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 threads per class for each 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 a good idea to change the default values. For computers with one or two processors, the default value is available, but for computers with more processors, 100 or 200 threads in a process can do more harm than benefit.

Note: Too many threads in a process tend to slow down the server because an additional context exchange causes the operating system to spend CPU cycles on maintenance 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, do not let unnecessary pointers point to objects because they will keep the objects alive, and avoid objects with Finalize methods as much as they will cause more work later. In particular, never release a resource in a Finalize call, because the resource may be consuming memory until it is reclaimed by the garbage collector. Finally, this problem often has a devastating impact on the performance of the WEB server environment because 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 occurs whenever a first request to a directory is taken. If the pages in the catalog are not parsed and compiled, this feature will parse and compile all the pages in the directory in batches to make better use of the 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 gives ASP. NET 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 yet been compiled, performance may be poor when the WEB server parses and compiles them. To solve this problem, you can perform a pre-batch compilation. To do this, simply request a page from the application before it is activated, no matter which 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. Wait until the CPU is idle or there are no more compiler processes (such as csc.exe (C # compiler) or vbc.exe (Visual Basic compiler)) to start.

You should also try to avoid changing the assemblies in the \ Bin directory of your application. Changing the page causes the page to be re-parsed and compiled, and replacing the assembly in the \ Bin directory causes the directory to be fully re-compiled.

On large-scale sites with many pages, a better approach might be to design different directory structures based on how frequently the pages or assemblies are replaced by the plan. Pages that are not frequently changed can be stored in the same directory and pre-batched at specific times. Pages that change frequently should be in their own directories (up to hundreds of pages per directory) for quick compilation.

A WEB application can contain many subdirectories. Batch compilation occurs at the directory level, not at the application level.

18. Do not rely on exceptions in your code

Because exceptions greatly degrade performance, you should not use them as a way to control the normal program flow. Perform this action if it is possible to detect a state in your code that could cause an exception. Do not catch the exception itself until the state is processed. Common scenarios include checking for null, assigning a value to a String that will be parsed as a numeric value, or checking for a specific value before applying a mathematical operation. The following example shows the code that could cause an exception and the code that tests for the presence of a certain state. 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 method provides very efficient buffering and connection services. 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 using a single call to the Response.Write method to connect strings.

Response.Write ("a");
Response.Write (myString);
Response.Write ("B");
Response.Write (Myobj.tostring ());
Response.Write ("C");
Response.Write (MYSTRING2);
Response.Write ("D");

20. Leave the buffer open unless you have a specific reason to turn it off

Disabling buffering of Web forms pages can result in a lot of performance overhead.

21. Save the server control view state only when necessary

Automatic view state management is a feature of server controls that enable server controls to repopulate their property values on round trips (you do not need to write any code). However, because the view state of the server control is round-tripping to the server in a hidden form field, the feature does have a performance impact. You should be aware of the circumstances under which view state can be helpful, 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 example of the DataGrid server control.

You can also disable view state for the entire page by using the @ Page directive. This is useful when you are not sending back to the server from the page:
Note The EnableViewState property is also supported in the @ Control directive, which allows you to control 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 by including the Trace= "true" property in the @ Page directive and view the Viewstate column of the Control Hierarchy table. For information about tracing and how to enable it, see ASP.

22. Avoid unnecessary round trips to the server

While it is likely that you want to use as much of the time and code-saving features of the Web Forms page framework as possible, it is not appropriate to use the ASP. NET server control and postback event handling in some cases.

Typically, you only need to initiate a round trip 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 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 results in a round-trip process.

If you develop custom server controls, consider having them render client code for browsers that support ECMAScript. By using server controls in this way, you can significantly reduce the number of times that information is sent to the WEB server unnecessarily.

Use Page.IsPostBack to avoid unnecessary processing of round trips

If you write code that handles postback processing for a server control, you may sometimes need to execute additional code when the page is first requested, rather than when the user sends the HTML form that is contained in the page. Use the Page.IsPostBack property to conditionally execute code, depending on whether the page was 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 the first time the page is requested.

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 ();
}
}
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, execute the code. If the 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 may be rendered on the output page. If you do not run the check, processing will still be performed for the Page_Load event and any server control events on the page.

23. Disable the session state when it is not in use

Not all applications or pages require session state for a specific user, and you should disable session state for any application or page that does not require session state.
To disable session state for a page, set the EnableSessionState property in the @ Page directive to false.
Note If the page requires access to session variables but does not intend to create or modify them, the EnableSessionState property in the @ Page directive is set to ReadOnly.
You can also disable session state for the XML Web services method. For more information, see XML Web Services created with 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.

24. Carefully select the 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 a SQL Server database. Each approach has its own advantages, but in-process session state is by far the fastest solution. If you store only a small amount of volatile data in session state, we recommend that you use an in-process provider. Out-of-process solutions are primarily used to scale applications across multiple processors or multiple computers, or when the server or process restarts without data loss. 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 facilitates program development, but can also result in a loss of performance, as users produce a round-trip to the server side each time the server-side control is operated. Therefore, it is not necessary to use server Control sparingly.

. ASP. NET Application Performance Testing

Before you perform a performance test on an ASP. NET application, you should ensure that the application is error-free and functioning correctly. Specific performance tests can be performed using the following tools:
The Web Application Strees tool (WAS) is a free test tool released by Microsoft that can be
 
[Url=http://webtool.rte.microsoft.com/]http://webtool.rte.microsoft.com/[/url]
Download. It can simulate hundreds of thousands of users at the same time access to the Web application requests, on the server to form a traffic load, so as to achieve the purpose of testing, can generate average TTFB, average TTLB performance summary report.
Application Center Test (ACT) is a test tool that comes with the Enterprise Edition of Visual Studio.NET and is the Web application Testing tool officially supported by Microsoft. It intuitively generates chart results, more functionality than was, but does not have the ability to test multiple clients simultaneously.

The performance counters in the server operating system Administrative tools allow you to monitor the server for application performance.

This article refers to self-http://www.cnblogs.com/lizhao-life/p/3936064.html

Asp. The methods used to optimize performance in net

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.