How to Improve program performance with ASP (i)

Source: Internet
Author: User
Tags add numbers connection pooling

"Summary" I'm just offering a few tips that I think will help improve the ability to write high-performance ASP. The technique for improving ASP. NET performance is just a start, and for more information please refer to "Improving ASP. NET Performance".

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.

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.

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

Str. Append (Num. ToString ()); Add Value num

Response.Write (str. ToString); Show Operation results

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.

<%@ 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 defer the creation of the object until the preceding 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)
%>

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.

<%@ 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 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 profile <processModel> node.

Note that worker threads are used to process 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 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 that 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.

How to Improve program performance with ASP (i)

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.