The following guidelines list specific technologies, you can use these techniques to ensure that the selected code reaches an acceptable level of performance.
Disable it when you do not use a session state. Not all applications or pages need to be targeted for specific users, and you should disable session status for any applications or page that does not require a session state. To disable the session state of the page, please
@Page
The EnableSessionState property in the instruction is set to false. For example, <% @ page enablessionState = "false"%>.
Note If the page needs to access the conversation variable, but not intended to create or modify them,
@ Page Directive
EnableSessionState property is set to
Readonly.
The session status of the XML Web Services method can also be disabled. For more information, see XML Web Services created using ASP.NET and XML Web Services client. To disable the application's session state, set the MODE property to OFF in the sessionState configuration section of the application web.config file. For example,
Page.ispostback
Avoid performing unnecessary processing on the round-trip process. If you write the code for processing the server control return process, you may need to perform other code when you first request a page instead of the code that is executed when the user is included in the HTML form included in this page. Depending on whether the page is generated by the response server control event, use the page.ispostback attribute to execute the code. For example, the following code demonstrates how to create a database connection and command, which is bound to the data when the page is requested.
DataGrid
Server controls. [Visual Basic]
SUB Page_Load (Sender As Object, E as Eventargs)
'Set up a connection and command here.
IF not (page.ispostback)
DIM Query As String = "SELECT * from authors where firstname like '% Justin%'" MyCommand.Fill (DS, "Authors")
MyDataGrid.Database
END IF
End Sub [C #]
Void Page_Load (Object Sender, Eventargs E) {
// set up a connection and common here.
IF (! page.ispostback) {
String query = "select * from authors where firstname Like '% Justin%'"
MyCommand.Fill (DS, "Authors");
MyDataGrid.databind ();
}
} Due to each request, the Page_Load event is executed, the above code checks if the iSPostBack property is set to false. If yes, execute the code. If this property is set to True, the code is not executed.
Note If this check is not running, the behavior of the back page will not change.
The code for the Page_Load event is executed before executing the server control event, but only the result of the server control event may be rendered on the output page. If you don't run the check, you will still be
Page_Load event and any server control event on this page performs processing.
Use the ASP.NET server control in an appropriate environment. Check your application code to make sure it is necessary to use the ASP.NET server control. Even if they are very easy to use, server controls don't always complete the best choice for tasks because they use server resources. In many cases, a simple rendering or data binding will complete the task. The following example demonstrates that using the server control is not the most efficient way to send values to the HTML sent to the client. Each method sends a path to the image that is displayed by the request browser, but is not the most advantageous method using server control, because the Page_Load event requires calling the server for processing. Instead, use the presentation statement or data binding expression. [Visual Basic]
Public ImagePath As String
SUB Page_Load (Sender As Object, E as Eventargs)
'... Retrieve Data for ImagePath Here ....
DataBind ()
End Sub
script>
<% - The span and img server controls are unecessary. -%>
The path to the image is:
<% - use data binding to substeute limited itrals instead. -%>
The path to the image is: <% # imagePath%>
<% - or use a simple rendering expression ...--%>
The path to the image is: <% = imagePath%>
[C #]
Public String ImagePath;
Void Page_Load (Object Sender, Eventargs E) {
//... RETRIEVE DATA for ImagePath Here ...
DataBind ();
}
script>
<% - The span and img server controls are unpassary ...--%>
The path to the image is:
<% - use data binding to substruction ...--%>
The path to the image is: <% # imagePath%>
<% - or use a simple rendering expression ...--%>
The path to the image is: <% = imagePath%>
There are still many other situations, in these cases rendering or data binding than using server controls, even when using server control templates. However, if you want to operate server control attributes, process server control events or save your server control or save your view status, use server controls. Save the server control view status only when necessary. Auto View Status Management is the functionality of the server control, which allows the server control to re-fill their attribute values (you do not need to write any code) on the round-trip process. However, because the view status of the server control is to and from the server in the hidden form field, this feature does have an impact on performance. You should know which case the view status will help, where it affects the performance of the page. For example, if you bind the server control to data on each round-trip process, replace the saved view status with the new value obtained from the data binding operation. In this case, the disable view status can save time. By default, view status is enabled for all server controls. To disable the view status, set the control's EnableViewState property to false, as shown in the following DataGrid server control sample.
The instruction disables the view status of the entire page. This will be very useful when you don't return from the page to the server: <% @ page enableViewState = "false"%>
note
@ Control
Support in the instruction
EnableViewState properties, this instruction allows you to control whether you enable view status for your user control.
To analyze the number of view status used by the server control, please enable the page of the Control Hierarchy table by incorporated the trace = "true" property in the @ page directive) and view the ViewState column of the Control Hierarchy table. For information on tracking and how to enable it, see ASP.NET Tracking. use
HttpResponse.write
The method is string in series. This method provides very effective buffering and connection services. However, if you are performing a wide connection, use multiple response.write calls. The techniques shown in the examples shown in the examples are faster than a single call connection string for the Response.Write method. [C #]
Response.write ("a");
Response.write (MyString);
Response.write ("b");
Response.write (MyObj.toString ());
Response.write ("c");
Response.write (mystring2);
Response.write ("D"); [Visual Basic]
Response.write ("a")
Response.write (MyString)
Response.write ("B")
Response.write (MyObj.toString ())
Response.write ("c")
Response.write (MyString2)
Response.write ("D") Unless there is a special reason to turn off the buffer, otherwise keep it open. The buffer to disable the web form page results in a lot of performance overhead. Do not rely on an exception in your code. Because exception greatly reduces performance, you should not use them as a way to control the normal procedure. If it is possible to detect a state in which the code may result in anomalous, do this. Do not capture an exception itself before processing the state. Common programs include: check NULL, assigning String that will be analyzed as numeric values
A value, or check the specific value before applying the mathematical operation. The following example demonstrates the code that can cause an abnormal code and whether there is a code that exists in some state. Both produce the same result. [C #]
// consider changing this ...
Try {
Result = 100 / NUM;
}
Catch (Exception E) {
Result = 0;
}
// ... to this.
IF (Num! = 0)
Result = 100 / NUM;
Else
Result = 0; [Visual Basic]
'Consider changing this ...
Try
Result = 100 / NUM
Catch (e as exception)
Result = 0
END TRY
// ... to this.
IF not (NUM = 0)
Result = 100 / NUM
Else
Result = 0
Endix is appropriately used garbage collector and automatic memory management of the public language runtime. Be careful not to assign excessive memory for each request, because this garbage collector will have to work more frequently. Also, don't let unnecessary pointer points to objects because they will keep objects active and should try to avoid the object of the Finalize method because they will lead to more work later. Especially in the finalize call, you will never release resources because resources may always consume memory before being recovered by garbage collector. Last this problem often causes devastating blow to the performance of the web server environment, because it is easy to exhaust a particular resource when waiting for Finalize runtime. For more information on garbage collectors and automatic memory management, see Automatic Memory Management. If there is a large web application, consider performing pre-compiled compilation. Batch compilation is performed whenever the first request for the directory. If the page in the directory is not analyzed and compiled, this feature will be batch and compile all the pages in the directory to better utilize disks and memory. If this takes a long time, the single page will be quickly analyzed and compiled so that the request can be processed. This feature gives ASP.NET performance because it compiles many pages as a single assembly. Access from the loaded assembly is fast than each page loads a new assembly. The disadvantage of compilation is that if the server receives many requests that have not been compiled, the performance may be poor when the web server is analyzed and compiled. To solve this problem, you can perform pre-compiled compilation. To this end, just request a page to it before the application is activated, no matter which page can be. Then, the page and its assembly will have been compiled when the user first accesses your site for the first time. There is no simple mechanism to know when batch compilation occurs. Need to wait until the CPU is idle or there is no more compiler process (such as CSC.EXE (C # compiler) or VBC.exe (Visual Basic Compiler)). It should also be avoided to avoid changing the assembly in the / bin directory of the application. Changing the page will result in re-analyze and compile this page, and the assembly in the replacement / bin directory will result in full re-approvement of the directory. On a large-scale site containing many pages, a better way may design different directory structures based on the frequently scheduled replacement page or assembly. The page that is not often changed can be stored in the same directory and perform pre-compiled time at a specific time. The frequent changes page should be in their own directory (up to hundreds of pages per directory) for quick compilation. The web application can contain many subdirectories. Batch compilation occurs in the directory level, not the application level. Recycling the process when running an ASP.NET web application on Internet Information Services 5.0. By default, the ASP.NET on IIS 5 is a request to serve it in a process external auxiliary process. This feature has been optimized to increase throughput. On the page of a lot of work, the throughput overhead running outside the process is not large (about 10%). Since there are many features and advantages to running ASP.NET in the auxiliary process outside the process, it is recommended to use it on the production site. For the reason for ensuring stability and performance, keep in mind the regular recycling process. After a longer time, leak resources and errors may affect the throughput of the web server. However, it is necessary to balance the recovery of regular recovery and overspeeding, because stop the auxiliary process, reload the page and re-acquire the resources and the overhead of the data may exceed the benefits of the recycling. ASP.NET web applications running on Windows Server 2003 using IIS 6.0 do not need to adjust process model settings. Adjust the number of threads for each accessibility process if necessary. The request structure of ASP.NET tries to achieve a balance between the number of threads and available resources. A application that uses sufficient CPU power is known that will determine the number of requests to be performed simultaneously based on the CPU power available for the request.
This technology is called threaded gates. But under certain conditions, the thread door control algorithm is not very effective. Gearing gates can be monitored in PerfMon by using the Pipeline Instance Count performance counter associated with the ASP.NET Applications Performance Object. When the page calls an external resource, such as database access or XML Web Services request, the page request usually stops and releases the CPU. If a request is waiting to be processed, there is a thread in the thread pool to be free, then this is waiting for the request will begin to be processed. Unfortunately, sometimes this may cause a large number of requests on the web server and a number of waiting threads that are waiting for, and they have an adverse effect on server performance. Typically, if the gate control is the response time of external resources, it is allowed to wait for resources to wait for resources, and there is no help to the throughput of the web server. To mitigate this situation, you can manually set the number of threads in the process by changing the MAXWORKERTHREADS and Maxioth attributes of the Machine.config> node. Note that the auxiliary thread is used to process the ASP.NET request, and the IO thread is used to serve data from files, databases, or XML Web Services.
The value assigned to these attributes is the maximum number of each CPU thread in the process. For dual-processor computers, the maximum number is twice the setting value. For the quadratic computer, the maximum value is four times the setting value. In any case, it is best to change the default value for computers with four or eight CPUs. For computers with one or two processors, the default value can, but for more processor's performance, one hundred or two hundred threads in the process are more harmful.
Note that too many threads in the process tend to reduce the speed of the server, because additional context exchange results in the operating system to spend the CPU cycle in the maintenance thread rather than the processing request.
use
Httpserverutility.transfer
Method is redirected between the page of the same application. Using the Server.Transfer syntax, use this method in the page to avoid unnecessary client redirectings. Make all modules in the request line as efficient as possible. Requesting all modules in the line There is an opportunity to run in each request. Therefore, it is critical to quickly triggering the code when requesting to enter and leave the module, especially in the code path that does not use the module function. The throughput test is performed when using and does not use modules and profiles, which is very useful for determining the execution speed of these methods. Early bindings were used in Visual Basic .NET or JScript code. In the past, developers like to use Visual Basic, VBScript and JScript reasons for the reasons for them are their so-called "non-type" nature. Variables do not require explicit type declarations and can be simply created by use. When allocated from a type to another, the conversion will be executed automatically. However, this convenience will greatly damage the performance of the application. Visual Basic is now supported by using the Option Strict Compiler instruction to support type security programming. In order to backward compatibility, the ASP.NET does not enable this option by default. However, in order to get the best performance, it is highly recommended to enable this option on the page. To enable Option Strict, include the strict property in
@Page
In command, or, for user controls, please include this attribute
@ Control
In the instruction. The following example demonstrates how to set this property and four variable calls to display how this property is to cause the compiler error. <% @ Page language = "vb" strake = "true"%>
<%
DIM B
DIM C AS STRING 'This Will Cause A Compiler Error.
A = "hello"
'This Will Cause A Compiler Error.
B = "world"
'This Will Not Cause A Compiler Error.
C = "!!!!!!"
'But this will cause a compiler error.
C = 0
%> JScript .NET also supports non-type programming, but it does not provide compiler instructions for early binding. If any of the following occurs, the variable is late binding:
Explicitly declared as Object. It is a field of classes that have no type declaration. It is a dedicated function or method member of the non-obvious type declaration, and it is impossible to use it to use it. The last difference is more complicated because if the JScript .NET compiler can infer the type according to the usage of the variable, it will optimize. In the example below, the variable A is early binding, but the variable B is late binding. VAR A;
VAR B;
A = "Hello";
B = "world";
B = 0; in order to achieve the best performance, when the JScript .NET variable is declared, it assigns a type. For example, VAR A: String. Migrate the intensive COM components to the managed code. .NET Framework provides a simple way to interact with traditional COM components. The advantage is that the new platform can be utilized while retaining existing investments. However, in some cases, the performance overhead of retaining the old assembly makes it worth migrating the components to the managed code. Each situation is different, deciding whether the best way to migrate components is to run performance measurements for Web sites. It is recommended that you study how to migrate any COM components that require a lot of calls to interact to the managed code. Many cases it is not possible to migrate old components to managed code, especially when the web application is initially migrated. In this case, one of the largest performance disorders is to seal data from a non-hosting environment to the hosted environment. Therefore, in the interaction, please perform as many tasks as possible at any end, and then make a large call rather than a series of small calls. For example, all strings in the public language runtime are Unicode, so you should convert all strings in the components into Unicode formats before calling managed code. In addition, any COM object or this resource is released. Thus, other requests can use them and minimize the performance issues caused by the release of garbage collectors later. Avoid single-threaded units (STA) COM components. By default, ASP.NET does not allow any STA COM components to run within the page. To run them, you must include the aspcompat = true property in the .aspx file in the @ page instruction. This will switch to the STA thread pool to the STA thread pool, and HTTPCONTEXT and other built-in objects can be used for COM objects. The former is also a performance optimization because it avoids any call to the multi-threaded unit (MTA) to the STA thread. With STA COM components, it may be greatly harmful and should be avoided as much as possible. If you must use the STA COM components, as in any InteroP scheme, you should perform a large number of calls during execution and send as much information as possible during each call. In addition, be careful not to create any STA COM components during the constructing 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 a STA thread that will run the page. This may have adverse effects on performance because the page must be constructed to complete the encapsulation processing between the MTA and STA threads. <% @ Page language = "vb" aspcompat = "true"%>
DIM mycomp as new mystacomponent ()
Public SUB Page_Load ()
Mycomp.name = "bob"
End Sub
script>
<%
Response.write (MyComp.SAYHELLO)
%>
The html> preferred mechanism is the creation of the delay object until the above-described code is executed under the STA thread, as shown in the example below. <% @ Page language = "vb" aspcompat = "true"%>
DIM Mycomp
Public SUB Page_Load ()
Mycomp = new mystacomponent ()
Mycomp.name = "bob" end sub
script>
<%
Response.write (MyComp.SAYHELLO)
%>
html> 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 components in a shared resource that can be accessed by other threads other than constructing its thread. Such resources include resources like cache and session status. Even if the STA thread calls the STA COM component, only the thread constructing this STA COM component can actually be called service, and this requires the encapsulation processing to call the creator thread. This encapsulation process may produce a significant performance loss and scalability. In this case, study the possibility of making COM components a MTA COM component, or a better way to migrate the code to make the object a managed object. Use the SQL Server stored procedure for data access. In all data access methods provided by .NET Framework, SQL Server-based data access is a recommended selection of high performance and scales web applications. Additional performance improvements can be obtained by using the compiled stored procedure instead of a special query by using the hosting SQL Server provider. For information on using the SQL Server stored procedure, see Will Stored Procedures for Commands. will
SqlDataReader
Types for quick only enter data cursors. The SqlDataReader class provides a way to read only data streams from the SQL Server database. If you have the case where you have allowed you to use it when you create an ASP.NET application, the SqlDataReader class provides a ratio
DataSet
Higher performance. The situation is thus because SqlDataReader reads data directly from the database connection using SQL Server native network data transmission format. In addition, SqlDataReader class is implemented
Ienumerable
Interface, the interface also allows you to bind data to server controls. For more information, see
SqlDataReader class
. For information on how ASP.NET access data, see Accessing Data over ASP.NET. Choose the data viewing mechanism for the page or application. There is an important trade-off based on how you choose to display data in a web form page, and there is an important weighing between facilities and performance. E.g,
DataGrid
Web server controls may be a convenient way to display data, but its overhead is often the greatest in terms of performance. In some simple situations, you may be effective by generating appropriate HTML yourself, but custom and browser orientation will quickly offset the additional efficacy.
Repeater
The web server control is a compromise for convenience and performance. It is efficient, customizable and programmable. As long as it is possible, the cache data and page output. ASP.NET provides some simple mechanisms that cache these page output or data without requiring dynamic calculation page output or data for each page. In addition, the performance of these pages can be optimized by designing the cached pages and data requests to be cached (especially the area where the volume is expected to be larger in the site). Compared with any Web Forms for .NET Framework, properly use the cache can better improve the performance of the site, sometimes this increase is superior. There are two points to pay attention to using the ASP.NET cache mechanism. First, don't cache too much. Cache is overhead, especially in memory use. Do not cache items that are easy to recalculate and rarely used. Second, the validity period given to the cache is not too short. Items that have expired will result in unnecessary turnover in the cache and often lead to more code clearance and garbage collection. If you are concerned about this issue, monitor the Cache Total Turnover Rate Performance Counter associated with the ASP.NET Applications Performance Object. High turnover rates may explain that there is a problem, especially when the item is removed before expire. This is also called memory pressure. For information on how to cache page output and data request, see the ASP.NET cache function. For applications that are widely dependent on external resources, consider enabling network gardening on multiprocessor computers. The ASP.NET process model helps enable scaling on multiprocessor computers, distribute work to multiple processes (one each CPU), and each process sets the processor relationship to its CPU. This technology is called network gardening. If the application uses a slower database server or a COM object with external dependencies (here just mentioned two possibilities), it is beneficial to enable network gardeners for your application. However, before deciding to enable network gardening, you should test the implementation of the application in the online garden. Be sure to disable debug mode. Always remember to disable debug mode before deploying production applications or performs any performance measurements. If debug mode is enabled, the performance of the application may be very affected. For syntax information for setting debug mode for the application in the web.config file, see the ASP.NET setting schema
. Optimize the web server computer and the configuration file for a specific application to meet your specific needs. By default, the ASP.NET configuration is set to enable the most extensive features and to adapt to the most common solutions. Therefore, application developers can optimize and change certain configurations in the functions used by the application to improve the performance of the application. The following list is some options you should consider.