Prompt for fine-tuning ASP. NET performance

Source: Internet
Author: User
Any programming model has common performance defects, and ASP. NET is no exception. This section describes how to avoid Code Performance bottleneck.

  1. Disable session status when not in use: Not all applicationsProgramOr pages must be based on the session Status of each user. If not, disable it. This can be easily achieved through the following page-level commands:

    <% @ Page enablesessionstate = "false" %>

    Note:If the page needs to access session variables without creating or modifying them, set the command valueReadonly. You can also disable the session status for XML Web Service methods. See use objects and internal objects in the XML Web Service Section.

  2. Select the session Status provider with cautionASP. 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 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, use the in-process provider. Out-of-process solutions are mainly used for Web garden and web farm solutions, or for cases where data cannot be lost when the server/process restarts.

  3. Avoid excessive round-trip with the server: The Web forms page framework is one of the best functions of ASP. NET, because it can significantly reduce the amount of code required to complete a task. Programming access to page elements using server controls and sending-back events to process models is undoubtedly the most time-saving feature. However, there are appropriate and inappropriate ways to use these features. It is important to know when to use them.

    Applications usually need to go back and forth to the server only when retrieving or storing data. Most data operations can be performed on the client during the round-trip. For example, you can verify the form items on the client before submitting data. Generally, if you do not need to relay the information back to the server, you should not switch back to the server.

    If you write your own server controls, consider making them present client code for the superior (ecmascript supported) browser. By using the "smart" control, you can significantly reduce the number of unnecessary clicks on Web servers.

  4. Use Page. ispostback to avoid additional work on the round-trip : To process server control sending back, you usually need to execute the code on the first request page. This code is different from the code used for round-trip when initiating an event. If you check Page. ispostback The code can be executed according to the conditions, depending on whether there is an initial request to the page or a response to the server control event. This seems obvious, but you can ignore this check without changing the page behavior. For example:


      
                 
                  
                 
      
                 
                  
                 
      
                 
                  
                 
    C # VB JScript  

    Page_loadThe event is executed on all requests, soPage. ispostbackTo processButton_clickWhen an event is returned, the first query is not executed. Note that even if this check is not performed, the page behavior will not change, because the binding in the first query will be in the event handlerDatabindCalls are overturned. Remember, this simple performance improvement is easy to ignore when writing pages.

  5. Exercise caution when using server controls : Although server controls are easy to use, they are not always the best choice. In many cases, simple rendering or replacement of data binding can accomplish the same thing. For example:

      <% -- the span and IMG server controls are unecessary... -- %> the path to the image is:  
    " runat="server ">
    <% -- use databinding to substitute literals instead... -- %> the path to the image is: <% # ImagePath %>

    <% -- or a simple rendering expression... -- %> the path to the image is: <% = ImagePath %>
      <% -- the span and IMG server controls are unecessary... -- %> the path to the image is:  
    " runat="server ">
    <% -- use databinding to substitute literals instead... -- %> the path to the image is: <% # ImagePath %>

    <% -- or a simple rendering expression... -- %> the path to the image is: <% = ImagePath %>
      <% -- the span and IMG server controls are unecessary... -- %> the path to the image is:  
    " runat="server ">
    <% -- use databinding to substitute literals instead... -- %> the path to the image is: <% # ImagePath %>

    <% -- or a simple rendering expression... -- %> the path to the image is: <% = ImagePath %>
    C # VB JScript  

    In this example, the server control is not required to substitute the value into the result HTML sent back to the client. This method applies in many other cases, even in the server control template. However, if you want to programmatically manipulate control properties, process events from them, or save events using their statuses, the server control is more suitable. Check the use of server controls and find the code that can be optimized.

  6. Avoid excessive Server Control view statuses: Automatic status management is a function that enables server controls to repopulate their values during a round-trip without writing any code. However, this function cannot be used at will, because the control status is passed in and out of the server in the hidden form field. UnderstandViewstateWhen is it helpful or not. For example, if you bind a control to data in each round trip (as shown in the Data Grid example in Article 4), the control is not required to maintain its view status, because in any case, any re-filled data will be erased.

    By default, all server controls are enabledViewstate. To disable itEnableviewstateSet property to false, as shown in the following example:

    <Asp: DataGrid enableviewstate = "false" datasource = "..." runat = "server"/>

    You can also disable it at the page level.Viewstate. This is useful when you do not initiate a response from a page, as shown in the following example:

    <% @ Page enableviewstate = "false" %>

    Note,User ControlThe command also supports this attribute. To analyze the number of view States used by server controls on the page, enable tracing and view the view Status column in the control hierarchy table. For more information about the tracing feature and how to enable it, see application-level tracking history.

  7. Use response. Write for string connection : Use the httpresponse. Write Method for string connection on the page or user control. This method provides very effective buffering and connection services. However, if you want to execute a large number of connections, use the method in the following example (that is, multiple calls Response. Write ). Response. Write The method must be fast.

     response. write ("A"); response. write (mystring); response. write ("B"); response. write (myobj. tostring (); response. write ("C"); response. write (mystring2); response. write ("D"); 
     response. write ("A") response. write (mystring) response. write ("B") response. write (myobj. tostring () response. write ("C") response. write (mystring2) response. write ("D") 
     response. write ("A"); response. write (mystring); response. write ("B"); response. write (myobj. tostring (); response. write ("C"); response. write (mystring2); response. write ("D"); 
    C # VB JScript
  8. Do not rely on exceptions in the code : Exceptions are a waste of resources and should be avoided in the Code as much as possible. Never use exceptions as a way to control the regular program flow. If you can detect a condition that causes an exception in the code, you should do so instead of waiting until the exception is caught before processing the condition. Common solutions include checking null values, assigning strings that are analyzed as numeric values, or checking specific values before applying mathematical operations. For example:

     // consider changing this: Try {result = 100/num ;} catch (exception e) {result = 0;} // to this: If (num! = 0) Result = 100/num; else result = 0; 
     'consider changing this: try result = 100/numcatch (E as exception) Result = 0end try // to this: if not (num = 0) result = 100/numelse result = 0end If 
     // consider changing this: try {result = 100/num;} catch (E: exception) {result = 0;} // to this: If (num! = 0) Result = 100/num; else result = 0; 
    C # VB JScript
  9. early binding in Visual Basic or JScript code : One of the advantages of Visual Basic, VBScript, and JScript is that they have no type. You only need to use them to create variables without explicit type declarations. The conversion is also automatically executed when one type is assigned to another. This is both an advantage and a disadvantage, because in terms of performance, late binding is convenient but expensive.

    Visual Basic supports type-safe programming by using special Option strict compiler commands. For backward compatibility, ASP. NET does not enable Option strict by default. However, to achieve optimal performance, you should use the strict attribute on the page or use the control command to enable Option strict for the page:

     <% @ page Language = "VB" strict = "true" %> <% dim bdim C as string 'This causes A compiler error: A = "hello" 'This causes a compiler error: B = "world" 'This does not: c = "!!!!!! "'But this does: c = 0%> 

    JScript also supports non-type programming, but it does not provide compiler commands that force early binding. Variables that meet the following conditions are bound later:

    • it is explicitly declared as an object.
    • it is a field of the class without type declaration.
    • it is a dedicated function/method member without explicit type declaration and cannot deduce the type from its use.

    the last feature is complex. If the JScript compiler can infer its type based on the use of variables, it will be optimized. In the following example, variable A is bound earlier, and variable B is bound later:

     var A; var B; A = "hello"; B = "world"; B = 0; 

    for optimal performance, declare the JScript variable as a type. For example, "Var A: string ".

  10. Port a large number of called COM components into managed code:. NET Framework is a very easy way to operate with traditional COM components. The advantage is that the new platform can be used while the existing code is retained. However, in some cases, the performance cost of retaining old components exceeds the cost of migrating components to managed code. Each scenario is special, and the best way to determine the content to change is to measure the performance of the site. However, the performance impact of COM interaction is usually proportional to the number of function calls or the amount of data that is blocked from unmanaged code to managed code. Because of the number of communications between each layer, the component that requires interaction with a large number of calls is called "chatty ". Porting such components to fully-hosted code should be considered to benefit from the performance gains provided by the. NET platform. Alternatively, you can consider re-designing components to request less calls or sending more data at a time.

  11. Use SQL stored procedures for data access: Among all the data access methods provided by the. NET Framework, SQL-based data access is the best choice for generating scalable Web applications with the best performance. When using hosted SQL providers, you can use compiled stored procedures instead of special queries for additional performance improvements. For examples of using SQL stored procedures, refer to the server-side data access section in this tutorial.

  12. Use sqldatareader to obtain the forward read-only data cursor:SqldatareaderThe object provides a forward read-only cursor for the data retrieved from the SQL database. IfSqldatareaderSuitable for your situation, it is a ratioDatasetBetter choice. BecauseSqldatareaderSupportedIenumerableYou can even bind a server control. UsageSqldatareaderSee the server-side data access section in this tutorial.

  13. Cache data and output as much as possibleThe ASP. NET programming model provides a simple mechanism to cache the output or data of pages for each request without the need to dynamically compute them. When designing a page, you can consider using the cache to optimize the areas where maximum traffic is expected in the application. The proper use of cache can enhance the performance of the site, and sometimes even increase by an order of magnitude or more, which is beyond the reach of any other functions of the. NET Framework. For more information about how to use cache, see the cache service section in this tutorial.

  14. Enable Web garden for multi-processor computers: Asp. net Process Model helps enable scalability on a multi-processor computer, distributes work to multiple processes (one CPU per worker), and each process sets the processor relationship to its CPU. This technology is calledWeb gardeningIt can significantly improve the performance of some applications. To learn how to enable Web gardening, see use process models.

  15. Do not forget to disable debugging mode: In ASP. NET Configuration<Compilation>Control whether the application is compiled in debug mode. The debugging mode seriously reduces performance. Before deploying production applications or measuring performance, always remember to disable the debug mode. For more information about the debugging mode, see the chapter titled SDK debugger.
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.