ASP. NET Optimization

Source: Internet
Author: User
. NET Framework developer Guide  
Develop high-performance ASP. NET Applications

The following guidelines list specific technologies that you can use to ensure that the written code reaches an acceptable performance level.

  • Disable a session when the session status is not used.Not all applications or pages need to be specific to the user's session status. You should disable the session status for any applications or pages that do not need the session status.

    To disable the page session statusEnablesessionstateSet propertyFalse. For example,<%@ Page EnableSessionState="false" %>.

    Note:If the page needs to access session variables without creating or modifying them@ PageIn the commandEnablesessionstateSet propertyReadonly.

    You can also disable the session Status of the XML Web Services method. For more information, see XML Web Services created using ASP. NET and XML Web Services clients.

    To disable the session Status of an application, go toSessionstateIn the configuration sectionModeSet propertyOff. For example,<sessionstate mode="off" />.

  • Select the session Status provider carefully.ASP. NET provides three different methods for storing application session data: in-process session Status, out-of-process session status as a Windows service, and out-of-process session Status in the SQL Server database. Each method has its own advantages, but the in-process session status is the fastest solution so far. If you only store a small amount of data that is prone to loss in the session state, we recommend that you use in-process providers. Out-of-process solutions are mainly used to scale applications across multiple processors or computers, or to prevent data loss during server or process restart. For more information, see ASP. NET status management.
  • Avoid unnecessary round-trip to the server.Although you may want to use the time-saving and code-saving functions of the web forms page framework as much as possible, ASP. NET Server controls and sending back events cannot be used in some cases.

    Generally, you only need to start the round-trip process to the server when retrieving or storing data. Most data operations can be performed on clients during the round-trip process. For example, it is often possible to verify user input from an HTML form on the client before the data is submitted to the server. Generally, if you do not need to pass the information to the server to store it in the database, you should not write the code that leads to the round-trip process.

    If you develop custom server controls, consider making them present client code for browsers that support ecmascript. By using the server control in this way, you can significantly reduce the number of times information is not necessary to be sent to the web server. For more information, see developing ASP. NET Server controls.

  • UsePage. ispostbackAvoid unnecessary handling of the round-trip process.If you write the code for processing the Server Control sending and processing, you may sometimes need to execute other code on the first request page, instead of the Code executed when the user sends an HTML form contained in the page. UsePage. ispostbackThe property executes the code conditionally. For example, the following code demonstrates how to create a database connection and command. This command binds data to the DataGrid server control when you request this page for the first time.
    [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.DataBind()    End If    End Sub    [C#]       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 each request is executedPage_loadEvent, the above Code checkIspostbackWhether the attribute is setFalse. If yes, the code is executed. If this attribute is setTrue, The Code is not executed.

    Note:If you do not run this check, the page will not be changed.Page_loadThe Event code is executed before the Server Control event is executed, but only the results of the server control event can be displayed on the output page. If you do not run this checkPage_loadEvent and any server control event on the page are processed.

  • Use the ASP. NET Server Control in an appropriate environment.Check your application code to ensure that the use of ASP. NET Server controls is necessary. Even if they are very easy to use, the server controls are not always the best choice for completing tasks because they use server resources. In many cases, a simple rendering or data binding can complete the task. The following example demonstrates that using a server control is not the most effective way to substitute a value into the HTML sent to the client. Each method sends the path of the image that will be displayed by the requesting browser, but using the server control is not the most advantageous method, becausePage_loadThe event requires that the server be called for processing. Instead, use a Presentation Statement or data binding expression.
    [Visual Basic]    <script language="VB" runat="server">    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: <span innerhtml='<%# imagePath %>' runat="server"/><br>    ' runat="server"/>    <br><br>    <%-- Use data binding to substitute literals instead.--%>    The path to the image is: <%# imagePath %><br>    ' />    <br><br>    <%-- Or use a simple rendering expression...--%>    The path to the image is: <%= imagePath %><br>    ' />    [C#]    <script language="C#" runat="server">    public String imagePath;    void Page_Load(Object sender, EventArgs e) {    //...Retrieve data for imagePath here...    DataBind();    }    </script>    <%-- The span and img server controls are unecessary...--%>    The path to the image is: <span innerhtml='<%# imagePath %>' runat="server"/><br>    ' runat="server"/>    <br><br>    <%-- Use data binding to substitute literals instead...--%>    The path to the image is: <%# imagePath %><br>    ' />    <br><br>    <%-- Or use a simple rendering expression...--%>    The path to the image is: <%= imagePath %><br>    ' />

    In many other cases, rendering or data binding is more effective than using server controls, even when using server control templates. However, if you want to programmatically manipulate the properties of the server control, process server control events, or save the view status, use the server control as appropriate.

  • Only save the Server Control view status when necessary.Automatic view status management is a function of the server control. This function enables the Server Control to re-fill their attribute values during the round-trip process (you do not need to write any code ). However, because the view status of the server control is redirected to and from the server in the hidden form field, this function does have an impact on performance. You should know under which circumstances the view status will be helpful and under which circumstances it will affect the page performance. For example, if you bind a server control to data during each round-trip process, the new value obtained from the data binding operation replaces the saved view status. In this case, disabling the view status can save processing time.

    By default, view status is enabled for all server controls. To disable view statusEnableviewstateSet propertyFalse, As shown in the following figure.DataGridServer Control example.

    <asp:datagrid EnableViewState="false" datasource="..." runat="server"/>

    You can also use the @ page command to disable the view status of the entire page. This is useful when you do not send the page back to the server:

    <%@ Page EnableViewState="false" %>

    Note:@ Control command is also supportedEnableviewstateAttribute, which allows you to control whether the view status is enabled for the user control.

    To analyze the number of view States used by server controls on the pageTrace = "true"Attributes are included in@ PageInstructions) Enable the tracing and view the pageControl hierarchyTableViewstateColumn. For more information about tracing and how to enable it, see ASP. NET tracing.

  • Disable the buffer unless otherwise specified.Disabling web form page buffering can cause a large amount of performance overhead.
  • Do not rely on exceptions in the code.Exceptions greatly reduce performance, so you should not use them as a way to control normal program processes. If the code may cause exceptions, perform this operation. Do not capture exceptions before processing the status. Common solutions include: CheckNull, Which is assigned to a string value that is analyzed as a numeric value, or to a specific value before applying a mathematical operation. The following example shows the code that may cause exceptions and test whether code in a certain status exists. The two generate the same results.
    [C#]    // Consider changing this...    try {    result = 100 / num;    }    catch (Exception e) {    result = 0;    }    // 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    // this.    If Not (num = 0)    result = 100 / num    Else    result = 0    End If
  • Use the Garbage Collector and Automatic Memory Management of the Common Language Runtime Library as appropriate.Be careful not to allocate too much memory to each request, because the Garbage Collector must do more work more frequently. In addition, do not point unnecessary pointers to objects because they will keep objects active and avoid includingFinalizeMethod objects, because they will lead to more work in the future. Especially inFinalizeDo not release resources during calls, because resources may always consume memory before being recycled by the garbage collector. In the end, this problem often causes a devastating impact on the performance of the Web server environment, becauseFinalizeDuring running, it is easy to use up a specific resource.

    For more information about the garbage collector and automatic memory management, see automatic memory management.

  • If there is a large web application, you can consider executing pre-Batch compilation.Each time a first request to a directory is sent, a batch compilation is performed. If pages in the directory are not analyzed and compiled, this function analyzes and compiles all pages in the directory in batches to make better use of disks and memory. If this takes a long time, a single page is quickly analyzed and compiled so that the request can be processed. This feature brings ASP. NET performance benefits because it compiles many pages into a single assembly. Accessing a page from a loaded assembly is faster than loading a new assembly on each page.

    The disadvantage of batch compilation is that if the server receives many requests for pages that have not yet been compiled, the performance may be poor when the web server analyzes and compiles them. To solve this problem, you can execute pre-Batch compilation. Therefore, you only need to request a page from the application before it is activated, regardless of the page. Then, when the user visits your site for the first time, the page and its assembly will have been compiled.

    There is no simple mechanism to know when batch compilation will take place. Wait until the CPU is idle or no more compiler processes (such as csc.exe (C # compiler) or vbc.exe (Visual Basic compiler) Start.

    Avoid changing the assembly in the \ bin directory of the application. Changing the page will cause re-analysis and compilation of the page, and replacing the assembly in the \ bin directory will cause full re-Compilation of the directory.

    On a large site that contains many pages, a better way is to design different directory structures based on the frequency of page replacement or Assembly planned. Pages that do not often change can be stored in the same directory and pre-compiled at a specific time. Frequently changed pages should be in their own directories (each directory can contain hundreds of pages at most) for quick compilation.

    Web applications can contain many subdirectories. Batch compilation occurs at the directory level, not the application level.

  • The process is reclaimed when an ASP. NET web application is running on Internet Information Service 5.0.By default, ASP. NET on IIS 5 serves the request to it in an out-of-process auxiliary process. This feature has been optimized to increase throughput. On a page that does a lot of work, the throughput overhead for off-process operations is not large (about 10% ). It is recommended to use ASP. net on the production site because it has many functions and advantages in the auxiliary process outside the process.

    To ensure stability and performance, remember to regularly recycle the process. After a long period of time, the leaked resources and errors may affect the Web server throughput. However, regular recovery and frequent recovery should be balanced, because the overhead of stopping auxiliary processes, reloading pages, and re-obtaining resources and data may exceed the benefits of recovery.

    You do not need to adjust the process model settings for ASP. NET web applications running on Windows Server 6.0 series running IIS 2003.

  • Adjust the number of threads for each worker process of the application if necessary.The request structure of ASP. net tries to strike a balance between the number of threads executing the request and the available resources. An application that uses sufficient CPU power is known. This structure determines the number of requests that can be executed simultaneously based on the CPU power available for requests. This technology is called thread-control. However, in some conditions, the thread-control algorithm is not very effective. By usingASP. NET ApplicationsPerformance object AssociationPipeline instance countPerformance counters, which can monitor thread-control in perfmon.

    When a page calls external resources, such as database access or XML Web Services requests, the page requests usually stop and release the CPU. If a request is waiting for processing and a thread in the thread pool is free, the waiting request will start to be processed. Unfortunately, sometimes this may lead to a large number of concurrent requests and many waiting threads on the Web server, which have adverse effects on server performance. Generally, if the gate factor is the response time of external resources, too many requests are waiting for resources, which is not helpful for the Web server throughput.

    To alleviate this problem, you can change the machine. config configuration file.<Processmodel>NodeMaxworkerthreads AndMaxiothreadsAttribute to manually set the number of threads in the process.

    Note:Auxiliary threads are used to process ASP. NET requests, while Io threads are used to provide services for data from files, databases, or XML Web Services.

    The value assigned to these attributes is the maximum number of threads in each CPU type in the process. For dual-processor computers, the maximum number is twice the set value. For a four-processor computer, the maximum value is four times the set value. In any case, it is best to change the default value for computers with four or eight CPUs. The default value can be used for computers with one or two processors. However, for computers with more processors, one hundred or two hundred threads in a process may cause more disadvantages.

    Note:Too many threads in the process will often reduce the server speed, because extra context switching causes the operating system to spend the CPU cycle on the maintenance thread rather than processing the request.

  • UseHttpserverutility. TransferMethod to redirect between pages of the same application.UseServer. TransferSyntax. Use this method on the page to avoid unnecessary client redirection.
  • Make all modules in the request pipeline as efficient as possible.All modules in the request pipeline have the opportunity to be run in each request. Therefore, it is critical to quickly trigger code when a request enters and leaves the module, especially in the code path that does not use the module function. The throughput test is executed when modules and configuration files are used and not used separately, which is very useful for determining the execution speed of these methods.
  • Use early binding in Visual Basic. Net or JScript code.In the past, one of the reasons why developers like to use Visual Basic, VBScript, and JScript was their so-called "non-typed" nature. Variables do not need explicit type declarations and can be created simply by using them. When the data is allocated from one type to another, the conversion is automatically executed. However, this convenience will greatly damage the performance of the application.

    Visual BasicOption strictCompiler commands to support type-safe programming. For backward compatibility, ASP. NET does not enable this option by default. However, to achieve optimal performance, we strongly recommend that you enable this option on the page. To enableOption strict, PleaseStrictThe attribute is included in the @ page command, or, for user controls, include this attribute in the @ control command. The following example shows how to set this attribute and calls four variables to show how this attribute causes a compiler error.

    <%@ Page Language="VB" Strict="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 commands that force early binding. If any of the following conditions occurs, the variable is bound late:

    • Explicitly declaredObject.
    • Is a field of the class without type declaration.
    • Is a special function or method member without explicit type declaration, and cannot deduce the type from its use.

    The last difference is complicated, because if the JScript. Net compiler can deduce the type based on the usage of the variable, it will be optimized. In the following exampleAIs bound earlier, but the variableBIs bound late.

    var A;    var B;    A = "Hello";    B = "World";    B = 0;

    To achieve optimal performance, assign a type to the JScript. Net variable when declaring it. For example,var A : String.

  • Migrate call-intensive COM components to managed code.. NET Framework provides a simple way to interact with traditional COM components. The advantage is that new technologies can be used while existing investments are retained. However, in some cases, retaining the performance overhead of the old component makes it worthwhile to migrate the component to the managed code. Every situation is different. The best way to determine whether to migrate components is to measure the Running Performance of web sites. We recommend that you study how to migrate any COM component that requires a large number of calls for interaction to managed code.

    In many cases, it is impossible to migrate legacy components to managed code, especially when a web application is initially migrated. In this case, one of the biggest performance barriers is to mail data from an unmanaged environment to a hosted environment. Therefore, in interactive operations, perform as many tasks as possible at any end, and then make a large call instead of a series of small calls. For example, all strings in the Common Language Runtime Library are Unicode, so all strings in the component should be converted to unicode format before calling managed code.

    In addition, after processing any COM objects or local resources, release them. In this way, other requests can use them and minimize the performance problems caused by later requests to the garbage collector to release them.

  • Avoid single-threaded unit (STA) COM components.By default, ASP. NET does not allow any Stas COM component to run on the page. To run them, you mustAspcompat = trueAttributes are included in@ PageCommand. In this way, the thread pool used for execution is switched to the sta thread pool, andHttpcontextAnd other built-in objects can be used for COM objects. The former is also a kind of performance optimization, because it avoids any call to mail multi-threaded units (MTA) to the sta thread.

    Using the sta COM component may greatly damage the performance and should be avoided as much as possible. If you must use the sta COM component, such as in any InterOP scheme, you should make a large number of calls during execution and send as much information as possible during each call. Also, be careful not to create any sta COM components during page construction. For example, in the following code, a page created by a thread will be instantiated during page construction.MySTAComponentThe thread is not the sta thread that will run the page. This may have a negative impact on performance, because to construct a page, you must complete the sending and receiving process between the MTA and the sta thread.

    <%@ Page Language="VB" ASPCompat="true" %>    <script runat=server>    Dim myComp as new MySTAComponent()    Public Sub Page_Load()    myComp.Name = "Bob"    End Sub    </script>    

    The preferred mechanism is to postpone object creation until the above code is executed in the sta thread in the future, 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>    

    We recommend that youPage_loadTo construct any COM component and external resources.

    Never store any Stas COM component in shared resources that can be accessed by other threads other than the threads that construct it. Such resources include resources such as cache and session status. Even if the sta thread calls the sta COM component, only the thread that constructs the sta COM component can actually serve the call, which requires sending and processing calls to the Creator thread. This mail may cause significant performance loss and scalability problems. In this case, consider the possibility of making the COM component an mta com component, or migrate code to make the object a hosted object.

  • Use SQL Server Stored Procedures for data access.Among all data access methods provided by. NET Framework, SQL Server-based data access is a recommended choice for generating high-performance, scalable Web applications. When using a hosted SQL Server Provider, you can use compiled stored procedures instead of special queries to obtain additional performance improvements. For information on using SQL Server Stored Procedures, see using Stored Procedures for commands.
  • SetSqldatareaderClass for fast data-only cursor. SqldatareaderClass provides a method to read data streams only retrieved from the SQL Server database. If you are allowed to use an ASP. NET application when you create itSqldatareaderClass provides higher performance than dataset class. This is becauseSqldatareaderUse the Local Network Data Transmission Format of SQL Server to directly read data from the database connection. In addition,SqldatareaderClass implements the ienumerable interface, which also allows you to bind data to the server control. For more information, see sqldatareader class. For information about how ASP. NET accesses data, see access data through ASP. NET.
  • Select a data view mechanism suitable for pages or applications.There are often important trade-offs between convenience and performance based on how you choose to display data on a web form page. For example, the DataGrid web server control may be a convenient and quick way to display data, but its overhead is often the largest in terms of performance. In some simple cases, it may be very effective to generate an appropriate HTML to present your own data, but custom and browser targeting will quickly offset the extra benefits you get. The repeater Web Server Control is a compromise between convenience and performance. It is efficient, customizable, and programmable.
  • Cache data and page output whenever possible.ASP. NET provides some simple mechanisms to cache the output or data of these pages when you do not need to request dynamic computing page output or data for each page. In addition, by designing pages and data requests to be cached (especially in areas where the site is expected to have a large amount of communication), you can optimize the performance of these pages. Compared with any web form function of. NET Framework, using the cache appropriately can improve the performance of the website. Sometimes this increase is more than an order of magnitude.

    There are two points to note when using the ASP. NET cache mechanism. First, do not cache too many items. Each item in the cache has an overhead, especially for memory usage. Do not cache items that are easy to recalculate and rarely used. Second, the period of validity allocated to cached items should not be too short. Items that expire soon will result in unnecessary turnover in the cache, and often lead to more code cleanup and garbage collection work. If you are concerned about this issueASP. NET ApplicationsPerformance object AssociationCache total turnover ratePerformance counters. High turnover rate may indicate problems, especially when items are removed before expiration. This is also called memory pressure.

    For information about how to cache page output and data requests, see ASP. NET cache.

  • For applications that rely heavily on external resources, consider enabling network gardening on a multi-processor computer.ASP. net Process Model helps enable scalability on a multi-processor computer, distribute work to multiple processes (one CPU per worker), and each process sets the processor relationship to its CPU. This technology is called Web gardening. Enable Web gardening for your application if your application uses a slow database server or calls a COM Object with external dependencies (only two possibilities are mentioned here. However, before deciding to enable Web gardening, you should test how applications are executed in the Web garden.
  • Make sure to disable the debugging mode.Remember to Disable debug mode before deploying production applications or performing any performance measurements. If the debug mode is enabled, the performance of the application may be greatly affected. For more information about the syntax used to set the debugging mode for the application in the web. config file, see ASP. NET setting architecture.
  • Optimize configuration files for Web server computers and specific applications to meet your specific needs.By default, ASP. NET configuration is set to enable the widest range of features and adapt to the most common solutions. Therefore, application developers can optimize and modify some of the configurations based on the features used by the application to improve application performance. The following lists some options you should consider.
    • Only enable authentication for the desired application.By default, the authentication mode is windows, or NTLM is integrated. In most cases, it is best to disable authentication in the machine. config file and enable authentication in the web. config file for applications that require authentication.
    • Configure the application based on the appropriate request and response encoding settings.ASP. NET default encoding format is UTF-8. If your application is strictly ASCII, configure the application to use ASCII for a slight performance improvement.
    • Disable autoeventwireup for applications.In the machine. config fileAutoeventwireupSet propertyFalse, Means that the page does not match the method name and event or hook the two (for examplePage_load). If page developers want to use these events, they need to override these methods in the base class (for example, they need to override the page loading eventPage. onloadInstead of usingPage_loadMethod ). If disabledAutoeventwireup, The page will be slightly improved by leaving the event connection to the page author instead of automatically executing it.
    • Remove unused modules from the request processing pipeline.By default<Httpmodules>All functions of the node are retained as activated. Based on the features used by the application, you can remove unused modules from the request pipeline for a slight performance improvement. Check each module and its functions and customize it as needed.

      For example, if you do not use session status or output cache in an application<Httpmodules>Remove them from the list so that requests do not have to execute the entry and exit code for each module when no other meaningful processing is performed.

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: 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.